首页 > 解决方案 > 我的脚本无法解析复杂网页中的项目

问题描述

我使用 selenium 在 python 中编写了一个脚本,以item name从网页中抓取连接到每个评论者的不同评论者。很少有项目在单击see more按钮时显示很多评论者,很少有没有评论者。

我尝试以这样的方式编写脚本,以便它可以从登录页面获取所有项目链接,然后遍历每个链接,然后单击review tab按钮see more,最后收集审阅者并重复相同的操作,直到没有更多的物品了。

这里主要关注的是,当脚本单击see more按钮时,它会打开一个包含审阅者的新选项卡。

链接到登陆页面

链接到包含评论的此类项目之一

链接到包含完整评论的页面

到目前为止,这是我的尝试:

from urllib.parse import urljoin
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

url = "https://eatstreet.com/madison-wi/restaurants"

def get_information(driver,link):
    driver.get(link)
    #collecting all the links connected to item names
    itemlinks = [urljoin(url,item.get_attribute("href")) for item in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR,"a.restaurant-header")))]
    for itemlink in itemlinks:
        driver.get(itemlink)

        #check whether there is any review
        revitem = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"label[for='reviews']")))

        if revitem and (revitem.text != "Reviews (0)"):
            current = driver.current_window_handle
            wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,"label[for='reviews']"))).click()
            wait.until(EC.visibility_of_element_located((By.LINK_TEXT,'See More Reviews'))).click()
            wait.until(EC.new_window_is_opened)
            driver.switch_to.window([window for window in driver.window_handles if window != current][0])
            while True:
                for item in wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,'ul.reviews div.review .review-sidebar #dropdown_user-name'))):
                    print(item.text)

                try:
                    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR,".pagination-block a.next"))).click()
                    wait.until(EC.staleness_of(item))
                except Exception:break
            driver.switch_to.default_content()

if __name__ == '__main__':
    options = Options()
    options.add_argument("--disable-notifications")
    driver = webdriver.Chrome(chrome_options=options)
    wait = WebDriverWait(driver,10)
    try:
        get_information(driver,url)
    finally:  
        driver.quit()

我上面的脚本可以reviewers从包含评论的第一个可用项目中收集名称,但是timeout exception当它应该去下一个项目收集评论者姓名时它会抛出错误。这可能是因为当脚本switch to default content并尝试重复该操作时,新打开的选项卡被取消选中。

下图显示了如何显示查看更多按钮:

在此处输入图像描述

标签: pythonpython-3.xseleniumselenium-webdriverweb-scraping

解决方案


如果您需要关闭新窗口并返回初始窗口,请尝试更换

driver.switch_to.default_content()

driver.close()
driver.switch_to.window(current)

推荐阅读