【问题标题】:Scraping webpage with show more button使用显示更多按钮抓取网页
【发布时间】:2021-07-26 00:54:28
【问题描述】:

我想用“显示更多”按钮抓取谷歌学者页面。使用该平台的帮助解决我之前提出的问题,我编写了以下代码,以便单击“显示更多”按钮。但是,我仍然遇到问题。对于带有多个“显示更多”按钮的配置文件,只有第一个被点击。我不明白为什么会这样。我将不胜感激。

from selenium import webdriver
import time
from bs4 import BeautifulSoup
import pandas as pd

options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--incognito')
chrome_path = r"C:\Users\ish05\Desktop\python\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)

driver.get("https://scholar.google.com/citations?user=cp-8uaAAAAAJ&hl=en")
time.sleep(3)
show_more = driver.find_elements_by_tag_name('button')
for x in range(len(show_more)):
    if show_more[x].is_displayed():
      driver.execute_script("arguments[0].click();", show_more[x])
      time.sleep(3)

【问题讨论】:

    标签: javascript python selenium web-scraping xpath


    【解决方案1】:

    它运行一个的原因是因为它在每一页上都出现一个。

    您需要使用无限循环,然后在页面上搜索,如果有然后单击 else 没有更多按钮从循环中中断。

    from selenium import webdriver
    import time
    chrome_path = r"C:\Users\ish05\Desktop\python\chromedriver.exe"
    driver = webdriver.Chrome(chrome_path)
    
    driver.get("https://scholar.google.com/citations?user=cp-8uaAAAAAJ&hl=en")
    time.sleep(3)
    while True:
        try:       
            show_more = driver.find_element_by_xpath("//button[.//span[text()='Show more'] and not(@disabled)]")
            driver.execute_script("arguments[0].click();", show_more)
            print("Show more button clicked")
            time.sleep(2)
        except:
            print("No more Show more button")
            break
    

    您将在控制台上看到以下输出

    Show more button clicked
    Show more button clicked
    Show more button clicked
    Show more button clicked
    Show more button clicked
    No more Show more button
    

    【讨论】:

    • 太棒了!这行得通..我现在明白了这个问题......非常感谢!
    【解决方案2】:

    首先,我看到该页面上有 19 个标签名称为 button 的元素,而其中只有一个是 Show more 按钮,可以通过以下 xpath 定位://button[.//*[contains(text(),'Show more')]]
    所以只有点击这个元素会点击Show more,而点击其他按钮会执行其他动作,那里的一些按钮元素也是不可点击的。

    【讨论】:

    • 是的,我看到列表返回了许多元素,而整个页面中只有 5 个显示更多按钮...我很困惑为什么...谢谢!
    猜你喜欢
    • 2020-06-28
    • 1970-01-01
    • 1970-01-01
    • 2022-09-24
    • 1970-01-01
    • 2021-11-06
    • 2015-11-21
    • 2021-12-10
    • 2011-04-20
    相关资源
    最近更新 更多