Skip to main content
 首页 » 编程设计

python之使用 Python 抓取 html 内容中的内容

2024年12月31日13开发

中文网here主要描述一家公司的信息。由于包含类似内容的页面很多,所以我决定用 Python 学习数据爬虫。

基本代码

import requests 
from bs4 import BeautifulSoup 
page = requests.get('http://182.148.109.184/enterprise-  
info!getCompanyInfo.action?companyid=1000356') 
 
soup = BeautifulSoup(page.text, 'html.parser') 
source_content = soup.find(class_='rightSide').find(class_='content register').find(class_='formestyle') 

我要收集的信息

该图是在 Chrome 检查元素页面中捕获的。

可能这里中文不友好,我在这里创建了一个例子来更好地说明。

<th> the variable name </th> => For example, "company name", "company location" 
<td> the target data I want to save </td> 

我的问题

根据我的基本代码,source_content 中不包含任何信息。输出文件如下所示:

对比图1、2,可以看到经度、纬度的信息都没有了。

如何使用 Python 获取这些数据?任何建议将不胜感激

请您参考如下方法:

如果您在请求中提供Referer header ,则可以获得该信息,如下所示:

import requests 
from bs4 import BeautifulSoup 
 
url = 'http://182.148.109.184/enterprise-info!getCompanyInfo.action?companyid=1000356' 
page = requests.get(url, headers={'Referer' : url}) 
soup = BeautifulSoup(page.text, 'html.parser') 
 
table = soup.find(class_='formestyle') 
 
for tr in table.find_all('tr'): 
    row = [v.text for v in tr.find_all(['th', 'td'])] 
    print(row) 

这将显示以下类型的数据:

['地理坐标:', '经度:104.2153 \xa0\xa0纬度:31.3631'] 

如您所见,信息现已呈现。