我是新手,如果我搞混了什么,很抱歉。我正在用Python编写一个SeleniumWebScraper,从《纽约时报》的文章档案中删除所有标题和日期
在页面底部有一个“显示更多”按钮,每次点击它都会加载10篇以上的文章。因此,我基本上希望点击“显示更多”按钮,直到没有更多的文章要加载,然后在整个页面上搜索标题和日期。以下是我的尝试:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import pandas as pd
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_argument('disable-infobars')
driver=webdriver.Chrome(chrome_options=options,
executable_path=r"//usr/local/Caskroom/chromedriver/81.0.4044.69/chromedriver")
driver.get("https://www.nytimes.com/search?dropmab=true&endDate=20120103&query=§ions=Business%7Cnyt%3A%2F%2Fsection%2F0415b2b0-513a-5e78-80da-21ab770cb753&sort=best&startDate=20070101")
WebDriverWait(driver, 40).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='css-vsuiox']//button[@data-testid='search-show-more-button']")))
while True:
try:
WebDriverWait(driver, 40).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='css-vsuiox']//button[@data-testid='search-show-more-button']"))).click()
print("MORE button clicked")
except TimeoutException:
break
driver.quit()
headlines_element = browser.find_elements_by_xpath('//h4[@class="css-2fgx4k"]')
headlines = [x.text for x in headlines_element]
print('headlines:')
print(headlines, '\n')
dates_element = browser.find_elements_by_xpath("//time[@class='css-17ubb9w']")
dates = [x.text for x in dates_element]
print("dates:")
print(dates, '\n')
for headlines, dates in zip(headlines, dates):
print("Headlines : Dates")
print(headlines + ": " + dates, '\n')
但是当我运行脚本时,showmore按钮会点击它几次,然后随机点击其中一篇文章并离开。我还尝试将标题和日期抓取嵌套在While循环中,但我一直得到一个“TabError:缩进中制表符和空格的使用不一致”
请帮忙!谢谢
输出:
我觉得你在使用标签,我建议不要使用它
您可以使用以下选项之一
选项1:
在python代码中使用
autopep8
。只需使用这个命令autopep8 -i yourFileName.py
以下是
autopep8
:https://pypi.org/project/autopep8/的文档选项2:
相关问题 更多 >
编程相关推荐