python - 我的脚本无法解析复杂网页中的项目
问题描述
我使用 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
并尝试重复该操作时,新打开的选项卡被取消选中。
下图显示了如何显示查看更多按钮:
解决方案
如果您需要关闭新窗口并返回初始窗口,请尝试更换
driver.switch_to.default_content()
和
driver.close()
driver.switch_to.window(current)
推荐阅读
- python - 使用 statsmodels.api 使用 ols().fit() 时出错
- xamarin.android - 使用 MvvmCross 创建 OnBoarding 流程
- wso2esb - WSO2 ESB HL7 处理
- php - 不能在帖子控制器中“排除”类别
- linux - 检查 git 存储库中文件的文件版本而不下载它们
- html - 如何在表格边框之间包含间隙?
- c++ - 没有运算符 >> 对应于这些操作数
- tfs - VS Code:登录到 TFS 不是使用密码,而是使用智能卡
- angular - 如何根据不同组件中的某些表单值创建反应字符串?
- c++ - 在函数返回中返回对新分配的 shared_ptr 的尊重是否合法?