【问题标题】:Request to a multi-page address that changes pages without changing the url请求多页地址,在不更改 url 的情况下更改页面
【发布时间】:2021-11-27 14:43:09
【问题描述】:

我要请求这个网址:

https://www.codal.ir/CompanyList.aspx

这个url包含110个页面的表格,当页面改变时,url和新请求都没有改变。

这是我的代码:

import requests as req
req = req.Session()
isics = req.get("https://www.codal.ir/CompanyList.aspx")
print(isics.text)

但我只获得第一页信息。我打算通过请求和正则表达式从表格中提取所需信息,但如果您有其他方式,我会很高兴听到。感谢您帮助我获得整个页面。

【问题讨论】:

  • 我会准备一个答案,但我必须知道你是否可以使用Selenium。我将使用它来自动在页面之间导航。
  • 是的,我可以使用。我一直在寻找一种更快地使用请求库的方法,但如果你也解决了 selenium 的问题,我会很高兴。

标签: python api selenium beautifulsoup request


【解决方案1】:

我使用Selenium 在表格中导航。 requests 无法做到这一点,因为我们没有将我们重定向到表中新页面的链接。您可以在下面找到代码。

from bs4 import BeautifulSoup
from selenium import webdriver
import time

def get_company_links(links, driver):
    soup = BeautifulSoup(driver.page_source, "html.parser")
    rows = soup.select("table.companies-table tr")
    for row in rows:
        link = row.select_one("a")
        if(link): 
            links.append("https://www.codal.ir/" + link['href'])



options = webdriver.ChromeOptions()
#options.add_argument("--headless")
driver = webdriver.Chrome(options=options)
driver.get("https://www.codal.ir/CompanyList.aspx")

current_page_button = driver.find_element_by_css_selector('input[type="submit"].normal.selected')
page_number = int(current_page_button.get_attribute('value'))

while(True):
    get_company_links(links, driver)
    next_page_button = driver.find_element_by_css_selector('input#ctl00_ContentPlaceHolder1_ucPager1_btnNext')
    next_page_button.click()
    time.sleep(2)
    previous_page_number = page_number
    current_page_button = driver.find_element_by_css_selector('input[type="submit"].normal.selected')
    page_number = int(current_page_button.get_attribute('value'))
    if(previous_page_number == page_number):
        break  # no more page left 

print(links)

主要工作原理是浏览表格并收集公司网站的链接。当最后一页索引等于当前索引时,我们使用next 按钮导航并停止,这表明我们到达了表格的末尾。

【讨论】:

  • 感谢@Muhteva ,是的,它对解决问题很有用并缩短了解决方案,我只是做了一些小改动,为 Firefox 设置了 webdriver,将每个页面的“行”信息放在一个字符串,并使用正则表达式轻松提取我想要的信息。
  • 我很高兴能提供帮助。
猜你喜欢
  • 2012-06-02
  • 2014-11-06
  • 2016-01-19
  • 1970-01-01
  • 2020-10-31
  • 2016-10-28
  • 2011-11-06
  • 2012-11-05
  • 2016-05-25
相关资源
最近更新 更多