【问题标题】:how to scrape website data after clicking More button点击更多按钮后如何抓取网站数据
【发布时间】:2024-05-02 08:45:02
【问题描述】:

我正在尝试使用 BS4 + selenium 学习网络抓取。网址是tripadvisor

评论文本有一个 More SPAN,点击它会使用 AJAX 将更多文本加载到同一个 div 中。

但我的代码在单击更多按钮之前通过 selenium 输出评论文本。

我怎样才能等到使用 selenium 点击“更多”按钮为止

    from selenium import webdriver
from bs4 import BeautifulSoup


def openUrl(link):
    driver = webdriver.Firefox()
    driver.get(link)

    elem1 = driver.find_element_by_xpath("//span[@class='taLnk ulBlueLinks']")
    elem1.click()
    html_source = driver.page_source
    driver.quit()

    soup = BeautifulSoup(html_source, 'lxml')
    foundDiv = soup.findAll("div", {"class": "review-container"})
    for reviewContainer in foundDiv:

        ratingText = reviewContainer.select_one(".partial_entry").text
        print(ratingText)

openUrl("https://www.tripadvisor.in/Hotel_Review-g1010231-d1065009-Reviews-Radisson_Blu_Resort_Spa_Alibaug-Alibaug_Raigad_District_Maharashtra.html")

但 BS4 无需等待点击更多按钮即可抓取数据。

请帮忙

【问题讨论】:

  • 您可以使用selenium-python.readthedocs.io/… 列表中的项目来检查页面的可用性吗?
  • 页面和元素可用。单击更多时,通过 Ajax 获取一些额外的文本,并添加到现有文本中。我需要暂停 python 代码一段时间,直到填充新数据。

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

请参阅下面的 WebDriverWait 示例。

driver.get('https://www.tripadvisor.in/Hotel_Review-g1010231-d1065009-Reviews-Radisson_Blu_Resort_Spa_Alibaug-Alibaug_Raigad_District_Maharashtra.html')
moreButton = driver.find_element_by_css_selector("span.taLnk.ulBlueLinks")
moreButton.click()

wait = WebDriverWait(driver, 10)
element = wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, "div[data-reviewid='493434022'] div.loadingShade")))

html_source = driver.page_source
print(html_source)

【讨论】:

  • 我还没有尝试过,但是div[data-reviewid='493434022'],一直存在,是点击更多链接,额外的数据附加到同一个div中。没有创建新元素。
  • 无论如何我通过模拟 AJAX 请求在没有 Selenium 的情况下解决了它。不过感谢您的建议
  • @raju 对不起。我不明白你的cmets。 div[data-reviewid='493434022'] 只是评论的一个示例元素。我的代码单击“更多”,然后等到div[data-reviewid='493434022'] div.loadingShade 消失,然后获取更新的内容,包括已附加的额外数据。你能澄清一下你的问题是什么吗?
最近更新 更多