有不同的方法
-
正如 burak 提到的 selenium 使事情自动化
-
使用您的requests 并将parameters 添加到您的网址,因为您可以从表格上方的select 获得feed_cat 和parameter_cat。 更新 - 查看编辑部分
我的示例循环遍历 feed_cat 选择框的选项
soup.find('select',attrs={'name': 'feed_cat'}).find_all('option')[1:3]
(只需要第二和第三个选项来演示)
然后requests 使用这些参数
page = requests.get(url+'?feed_cat='+option['value']+'&parameter_cat=All', headers=headers)
最后你可以循环数据来生成你的数据框。
注意:在一个请求https://www.feedtables.com/fr/content/table-dry-matter?feed_cat=All&parameter_cat=All 中获取所有数据的简单方法将不起作用,您将收到服务器错误。
请求示例
import bs4
import requests
import pandas as pd
url = "https://www.feedtables.com/fr/content/table-dry-matter"
headers = {"user-agent": "Mozilla/5.0"}
page = requests.get(url, headers=headers)
soup = bs4.BeautifulSoup(page.text,'lxml')
data = []
for option in soup.find('select',attrs={'name': 'feed_cat'}).find_all('option')[1:3]:
page = requests.get(url+'?feed_cat='+option['value']+'¶meter_cat=All', headers=headers)
soup = bs4.BeautifulSoup(page.text,'lxml')
cases = soup.select_one('table.views-table.sticky-enabled')
th=[]
td=[]
for i in cases.find_all('th'):
th.append(i.text.strip())
for row in cases.find_all('tr')[1::2]:
td.append([i.get_text(strip=True) for i in row.find_all('td')])
data.append({'cat' : option.text, 'headers':th, 'data':td})
df=pd.DataFrame(data[0]['data'], columns=data[0]['headers'])
df
输出(执行示例看起来更好;))
Matière première MS % MAT % CB % MGr % MM % MMins % NDF % ADF % Lignine % ... GluDIS volaille g/kg GlyDIS volaille g/kg SerDIS volaille g/kg ProDIS volaille g/kg CED MJ/kg ConsP g P/kg CC g CO2eq/kg Acid. mol H+eq/kg Eutrophisation g PO4---eq/kg OS m²yr/kg
0 Avoine 100 10.8 13.1 5.4 2.9 1.2 35.7 16.3 2.6 ... 15 4.2 4 4.9 3.02›››3.23››› 3.32›››3.32››› 555›››566››› 0.0139›››0.014››› 61.23›››61.52››› 0.0002›››0.0002›››
1 Avoine décortiquée 100 12.8 4.5 3.1 2.5 1.2 12.8 5.3 1.9 ... 19.9 5.2 5.1 6.3
2 Avoine floconnée 100 10.8 13.1 5.4 2.9 1.2 35.7 16.3 2.6 ... 15 4.2 4 4.9
3 Blé dur 100 16.4 3 2 2.1 0.05 15.9 4.2 1.3 ... 48.2 5.5 7.2 16.3
编辑
将我的示例改进为以下使用pd.read_html()的更短的示例
import bs4
import requests
import pandas as pd
url = "https://www.feedtables.com/fr/content/table-dry-matter"
headers = {"user-agent": "Mozilla/5.0"}
page = requests.get(url, headers=headers)
soup = bs4.BeautifulSoup(page.text,'lxml')
df_list = []
for url in [url+'?feed_cat='+option['value']+'¶meter_cat=All' for option in soup.find('select',attrs={'name': 'feed_cat'}).find_all('option')][1:3]:
df_list.append(pd.read_html(url)[0])
df = df_list[0].dropna(how='all')
df