python - 由于无限页面加载,无法通过 python 中的 selenium 进行抓取
问题描述
我正在尝试提取一些新闻文章的内容。某些 url 需要登录才能访问完整内容。我决定使用 selenium 自动登录。但是,我无法提取内容,因为第一个 url 需要永远加载并且永远不会到达实际文本提取完成的地步。它最终抛出超时异常。
这是我的代码
for url in url_list:
chrome_options = Options()
ua = UserAgent()
userAgent = ua.random
options.add_argument(f'user-agent={userAgent}')
driver = webdriver.Chrome(ChromeDriverManager().install(), options = chrome_options)
driver.get(url)
time.sleep(5)
frame = driver.find_elements_by_xpath('//iframe[@id="wallIframe"]')
#Some articles require going through a paywall and some don't
if len(frame)==0:
text_element = driver.find_elements_by_xpath('//section[@id="main-content"]//article//p')
text = " ".join(x.text for x in element)
else:
text = log_in(frame)
driver.quit()
尽管代码从未到达过它,但这是我的 log_in 方法
def log_in(frame):
driver.switch_to.frame(frame[0])
driver.find_element_by_id("PAYWALL_V2_SIGN_IN").click()
time.sleep(2)
driver.find_elements_by_id("username")[0].send_keys(username)
time.sleep(2)
driver.find_elements_by_xpath('//button[text()="Continue"]')[0].click()
time.sleep(1)
driver.find_elements_by_id("password")[0].send_keys(password)
time.sleep(1)
element = driver.find_elements_by_xpath('//button[@type="submit"]')[0].click()
time.sleep(1)
text = parse_text(element)
我怎样才能解决这个问题?
解决方案
与其手动设置超时time.sleep
,不如使用WebDriverWait
with expected_conditions
; 这样,只有在满足特定条件时(例如,如果元素可见或元素可单击),才会对元素执行的操作。
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
try:
frame = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, '//iframe[@id="wallIframe"]')))
except TimeoutException:
print "Element not found."
推荐阅读
- python - 如何在 for 循环中设置单选按钮
- python-3.x - 无法读取没有错误/错误的串行数据
- java - 从 Firestore 检索数据到 ListView 不起作用
- flutter - 如何在 Flutter 中打印到热敏网络打印机?
- tensorflow - 如何设计一个最优的CNN?
- flutter - 为什么我的 Flutter JSON 数据没有从 setState 更新?
- material-ui - Material UI - 主题覆盖了错误的组件
- python - 给定一个简单的邻接矩阵,用 Python 找到十对顶点的最小边数
- ios - 如何取消对projectedValue 所做的更改
- python - Tensorflow Keras 错误“找不到算法!”