【问题标题】:how to loop pages using beautiful soup 4 and python and selenium?如何使用漂亮的汤 4 和 python 和 selenium 循环页面?
【发布时间】:2019-11-05 18:20:39
【问题描述】:

虽然我对硒有一些经验,但我对 Python 还是很陌生,第一次使用漂亮的汤。我正在尝试为所有附属号码抓取一个网站 ("http://cbseaff.nic.in/cbse_aff/schdir_Report/userview.aspx" )。

问题是它们在多个页面上(1 上 20 个结果,总计:21,000+ 个结果)

所以,我希望在某种可以迭代下一页 btn 的循环中刮掉这些,网页 URL 中的问题不会改变,因此没有模式。

好的,为此我已经尝试过,谷歌表导入 HTML/导入 XML 方法,但由于大规模的问题,它只是挂起。 接下来我尝试了 python 并开始阅读有关使用 python 进行抓取的内容(我是第一次这样做:))这个平台上的某个人建议了一种方法

(Python Requests/BeautifulSoup access to pagination)

我也在尝试做同样的事情,但收效甚微。

此外,要获取结果,我们必须首先使用关键字“a”查询搜索栏 --> 然后单击搜索。只有网站显示结果。

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by  import By
import time

options = webdriver.ChromeOptions()
options.add_argument("headless")
driver = webdriver.Chrome(executable_path=r"C:\chromedriver.exe",options=options)

driver.get("http://cbseaff.nic.in/cbse_aff/schdir_Report/userview.aspx")
#click on the radio btn
driver.find_element(By.ID,'optlist_0').click()

time.sleep(2)

# Search the query with letter A And Click Search btn
driver.find_element(By.ID,'keytext').send_Keys("a")
driver.find_element(By.ID,'search').click()

time.sleep(2)

next_button = driver.find_element_by_id("Button1")
data = []
try:
    while (next_button):    
        soup = BeautifulSoup(driver.page_source,'html.parser')
        table = soup.find('table',{'id':'T1'}) #Main Table
        table_body = table.find('tbody') #get inside the body
        rows = table_body.find_all('tr') #look for all tablerow
        for row in rows:            
            cols = row.find_all('td')  # in every Tablerow, look for tabledata
                for row2 in cols:
                    #table -> tbody ->tr ->td -><b> --> exit loop. ( only first tr is our required data, print this)

我期望的最终结果是跨多个页面的所有从属机构编号列表。

【问题讨论】:

  • 上面的代码不完整,但我在最后一行列出了下一个待办事项,

标签: python selenium selenium-webdriver web-scraping beautifulsoup


【解决方案1】:

在您的 while 循环中对代码进行少量补充:

next_button = 1 #Initialise the variable for the first instance of while loop

while next_button:
    #First scroll to the bottom of the page
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") 
    #Now locate the button & click on it
    next_button = driver.find_element(By.ID,'Button1')
    next_button.click()
    ###
    ###Beautiful Soup Code : Fetch the page source now & do your thing###
    ###
    #Adjust the timing as per your requirement
    time.sleep(2)

请注意,滚动到页面底部很重要,否则会弹出一个错误,声称 'Button1' 元素隐藏在页脚下。因此,使用脚本(在循环的开头),浏览器将向下移动到页面底部。在这里,它可以清楚地看到 'Button1' 元素。现在,找到元素,执行点击操作,然后让您的 Beautiful Soup 接管。

【讨论】:

  • 感谢您的回复,已添加滚动页面。但我仍然无法找到我在上面留下评论的 BS4 Loop 2 的导航。网站的设计有些困难
猜你喜欢
  • 2023-03-23
  • 2018-12-21
  • 2013-11-25
  • 1970-01-01
  • 1970-01-01
  • 2017-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多