对多页地址的请求,该地址在不更改url的情况下更改页面

2024-06-16 11:14:25 发布

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

我想请求此url:

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

A screenshot of the page

此url包含110个页面上的表,当页面更改时,url和新请求都不会更改

这是我的代码:

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

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


Tags: 代码httpsimport信息urliraswww
1条回答
网友
1楼 · 发布于 2024-06-16 11:14:25

我使用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按钮导航并停止,这表明我们到达了表的末尾

相关问题 更多 >