为了账号安全,请及时绑定邮箱和手机立即绑定

使用 Selenium 和 BeautifulSoup4 抓取动态加载的 Href 属性

使用 Selenium 和 BeautifulSoup4 抓取动态加载的 Href 属性

慕尼黑5688855 2023-05-09 09:58:38
我试图用 Selenium 和 BeautifulSoup4 抓取动态加载的 href 属性。当我查看网站的源代码时,href 属性为空但是当我单击检查元素时,href 属性将有一个链接。表示 href 属性是动态加载的。我怎样才能提取该链接?我正在尝试使用以下代码def Scrape_Udemy():    driver.get('https://couponscorpion.com/marketing/complete-guide-to-pinterest-pinterest-growth-2020/')    content = driver.page_source    soup = BeautifulSoup(content, 'html.parser')    course_link = soup.find_all('div',{'class':"rh_button_wrapper"})    for i in course_link:        link = i.find('a',href=True)        if link is None:           print('No Links Found')        print(link['href'])但是当我运行这个函数时,它正在打印 []。我正在使用 Chrome 驱动程序 我该如何解决这个问题。我想从网址https://couponscorpion.com/marketing/complete-guide-to-pinterest-pinterest-growth-2020/抓取免费优惠券代码链接
查看完整描述

1 回答

?
慕哥6287543

TA贡献1831条经验 获得超10个赞

两件事情

  1. 在获取页面源之前需要单击一个框

  2. 您的链接是span不是div

代码

import time

from selenium import webdriver

from bs4 import BeautifulSoup

driver = webdriver.Chrome(executable_path=r'c:\users\aaron\chromedriver.exe')

driver.get('https://couponscorpion.com/marketing/complete-guide-to-pinterest-pinterest-growth-2020/')

time.sleep(5)

driver.find_element_by_xpath('//button[@class="align-right primary slidedown-button"]').click()

content = driver.page_source

soup = BeautifulSoup(content, 'html.parser')

course_link = soup.find_all('span',{'class':"rh_button_wrapper"})

for i in course_link:

    link = i.find('a',href=True)

    if link is None:

        print('No Links Found')

    print(link['href'])

输出

https://couponscorpion.com/scripts/udemy/out.php?go=Q25aTzVXS1l0TXg1TExNZHE5a3pEUEM4SUxUZlBhWEhZWUwwd2FnS3RIVC96cE5lZEpKREdYcUFMSzZZaGlCM0V6RzF1eUE3aVJNaURZTFp5L0tKeVZ4dmRjOTcxN09WbVlKVXhOOGtIY2M9&s=e89c8d0358244e237e0e18df6b3fe872c1c1cd11&n=1298829005&a=0

解释

总是看看当你这样做时会发生什么driver.get(),有时在你可以获得页面源之前需要点击一些框。必须进行所有浏览器活动。


这是我们使用 XPATH 选择器在该框上找到要单击的元素。


//button[@class="align-right primary slidedown-button"]

这意味着


// - The entire DOM 

button - The HTML tag we want

[@class=""] - The HTML tag with class "" 

我通常会在访问元素之前等待一些时间,这个页面需要一段时间才能加载,而且通常你需要添加一些等待才能获得你想要的元素或页面的一部分。


有几种方法可以做到这一点,这里是使用模块时间的快速而肮脏的方法。有一些特定的方法可以使用硒来等待元素出现。我实际上尝试了这些,但无法让它发挥作用。


请在文档中和此处查看值得了解的特定部分。


如果您查看 HTML,您会发现链接位于span类元素后面rh_button_wrapper,而不是 div。


查看完整回答
反对 回复 2023-05-09
  • 1 回答
  • 0 关注
  • 124 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信