【问题标题】:Scraping dynamic website with filters python使用过滤器python抓取动态网站
【发布时间】:2021-04-13 03:15:36
【问题描述】:

我想在网站上刮一张桌子:https://www.feedtables.com/fr/content/table-dry-matter。问题是要使用过滤器才能获得所需的数据,否则您只能在进入网站后才能获得呈现的数据!请帮忙!

这是我用来抓取表格的代码:

import requests
import bs4 
import pandas as pd

URL = 'https://www.feedtables.com/fr/content/table-dry-matter'
page = requests.get(URL)

soup = bs4.BeautifulSoup(page.text,'lxml')
cases = soup.find('table', class_= 'views-table sticky-enabled cols-16')
headers=[]
for i in cases.find_all('th'):
    headers.append(i.text.strip())

Data=[]
for i in cases.find_all('td'):
    Data.append(i.text.strip())

chunks = [Data[x:x+16] for x in range(0, len(Data), 16)]
chunks

【问题讨论】:

    标签: python web-scraping dynamic


    【解决方案1】:

    有不同的方法

    1. 正如 burak 提到的 selenium 使事情自动化

    2. 使用您的requests 并将parameters 添加到您的网址,因为您可以从表格上方的select 获得feed_catparameter_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']+'&parameter_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']+'&parameter_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
    

    【讨论】:

    • 哇!伙计,这就是我喜欢编程社区的原因!非常爱兄弟!你摇滚!非常感谢!
    • 亲爱的!再次感谢您的编辑!
    【解决方案2】:

    你不能用 bs4 处理它。但是你可以使用 selenium 轻松完成。

    #Download chromedriver from https://chromedriver.chromium.org/downloads  
    #pip install selenium
    
    
        import time, os
        from selenium import webdriver
        from selenium.webdriver.common.keys import Keys
        
        chromedriver = "C:\\Program Files\Google\Chrome\Application\chromedriver"
        os.environ["webdriver.chrome.driver"] = chromedriver
    
        url_head = 'https://www.google.com/search?q="HOW+TO+USE+SELENIUM"'
        driver = webdriver.Chrome(chromedriver)
        driver.get(url)
    

    这就是您可以连接的方式。然后你可以像这样点击。

    driver.find_element_by_xpath('//html/body/div[1]/div/ul/li[3]').click()
    

    更多信息请查看:https://selenium-python.readthedocs.io/locating-elements.html

    【讨论】:

    • 非常感谢 der burak。这意味着我应该在这类网站上使用硒!再次感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 2010-09-17
    相关资源
    最近更新 更多