【发布时间】:2020-08-03 09:38:50
【问题描述】:
我一直在尝试获取新闻文章主页的所有 href。最后,我想创造一些东西,给我所有新闻文章中最常用的 n 个词。为此,我认为我需要先使用 href,然后一个接一个地单击它们。
在这个平台的另一个用户的大力帮助下,这是我现在得到的代码:
from bs4 import BeautifulSoup
from selenium import webdriver
url = 'https://ad.nl'
# launch firefox with your url above
# note that you could change this to some other webdriver (e.g. Chrome)
driver = webdriver.Chrome()
driver.get(url)
# click the "accept cookies" button
btn = driver.find_element_by_name('action')
btn.click()
# grab the html. It'll wait here until the page is finished loading
html = driver.page_source
# parse the html soup
soup = BeautifulSoup(html.lower(), "html.parser")
articles = soup.findAll("article")
for i in articles:
article = driver.find_element_by_class_name('ankeiler')
hrefs = article.find_element_by_css_selector('a').get_attribute('href')
print(hrefs)
driver.quit()
它给了我我认为的第一个href,但它不会遍历下一个href。它只是给我第一个 href 的次数与它必须迭代的次数一样多。有谁知道我如何让它进入下一个 href 而不是被困在第一个?
附言。如果有人对如何进一步完成我的小项目有一些建议,请随时分享,因为我还有很多关于 Python 和编程的知识要学习。
【问题讨论】:
标签: python selenium loops web-scraping href