【发布时间】:2021-02-22 05:17:44
【问题描述】:
我正在尝试在 python 中开发一个网络爬虫,给定一个网站,分析其 html 并搜索所有 href 标签,但是使用 Beautiful Soap 之类的库无法获取 html 页面的动态内容,事实上,我正在制作的爬虫还必须发现任何脚本生成的 hrefs。所以我发现了 Selenium 并制作了这个脚本:
driver = webdriver.Chrome()
driver.get(url)
driver.execute_script("return document.body.innerHTML")
time.sleep(15)
html = driver.page_source
print("HTML :", html)
links = []
elements = driver.find_elements_by_tag_name('a')
for elem in elements:
href = elem.get_attribute("href")
links.append(href)
return links
但是当我运行它时,我没有在 html 中找到我看到的内容,例如使用 Chrome 开发人员工具,所以我的问题是:如何获取页面的整个 html 以及生成的 html通过通用脚本?
要测试的网址:“https://www.lubecreostorepratolapeligna.it/it/cucine-lube/cucine-moderne/”
测试示例:我想获取目录中厨房图像的 href
注意由于WebDriverWait,我不想选择一个元素并等待它,因为我正在为任何网站创建通用爬虫,所以我没有要等待或搜索的特定元素,我只想获取动态内容一个通用的html。
如果有更好的库适合我的目的,请告诉我。
更新:我在这里找到了解决问题的方法是在 html 中搜索任何 iframe(页面的动态内容)然后导航它们的代码
options = Options()
options.add_argument('--headless')
browser = webdriver.Chrome(options=options)
browser.get(url_to_search_for)
soup = BeautifulSoup(browser.page_source, "html.parser")
browser.close()
iframe = []
for x in soup.find_all('iframe'):
print(x['src'])
if str in x['src']:
print('ciao')
iframe.append(x['src'])
for x in iframe:
try:
page = urllib.request.urlopen(x, timeout=20)
except HTTPError as e:
page = e.read()
soup = BeautifulSoup(page, 'html.parser')
for a in soup.find_all('a', href=True):
print("HREF IFRAME", a['href'])
【问题讨论】:
标签: python html selenium web-crawler