PythonWebScraping,如何使用RequestsHTML库单击“下一步”

2024-05-16 04:11:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python请求html模块从“https://fortune.com/global500/2019/search/”获取数据。我能够获得前100项(从第一页),因为该页启用了javascript。我们需要点击“下一步”加载第二页,目前我只得到前100项。你知道吗

当我在浏览器上单击“下一步”时,地址栏上的url不会改变。所以我不知道如何使用html请求获取下一页。你知道吗

from requests_html import HTMLSession

def get_fortune500():
    companies = []
    url = 'https://fortune.com/global500/2019/search/'
    session = HTMLSession()
    r = session.get(url)
    r.html.render(wait=1, retries=2)
    table = r.html.find('div.rt-tbody', first=True)
    rows = table.find('div.rt-tr-group')
    for row in rows:
        row_data = []
        cells = row.find('div.rt-td')
        for cell in cells:
            celldata = cell.text.lstrip('$').replace(',', '')
            row_data.append(celldata)
        companies.append(row_data)
    return companies

fortune_list = get_fortune500()
print(fortune_list)
print(len(fortune_list))

我真的很感谢你抽出时间。你知道吗


Tags: httpsdivcomurlsearchdatagethtml
2条回答

页面使用ajax,我强烈建议您使用selenium。 下面是单击“下一步”按钮的示例(只需单击一次)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
chromeoption = Options()
# chromeoption.add_argument(' headless')
browser = webdriver.Chrome(options=chromeoption)
browser.get("https://fortune.com/global500/2019/search/")
wait = WebDriverWait(browser,3,0.5)
wait.until(lambda diver:browser.find_element_by_xpath("""//*[@id="content"]/div[2]/div/div[2]/div/div[2]/div/div[3]/button"""))
next=browser.find_element_by_xpath("""//*[@id="content"]/div[2]/div/div[2]/div/div[2]/div/div[3]/button""")
next.click()

这是500人的名单

https://content.fortune.com/wp-json/irving/v1/data/franchise-search-results?list_id=2666483

此网站正在浏览器IndexedDB中存储此API的响应,之后只有前端控制。你知道吗

您可以找出从第一个请求读取响应的方法。你知道吗

相关问题 更多 >