python - 使用 python -selenium 进行网页抓取

标签 python selenium web-scraping beautifulsoup

我想从“news”类中抓取所有href内容(代码中提到了Url),我尝试了这段代码,但它不起作用......

代码:

from bs4 import BeautifulSoup
from selenium import webdriver

Base_url = "http://www.thehindubusinessline.com/stocks/abb-india-ltd/overview/"

driver = webdriver.Chrome()
driver.set_window_position(-10000,-10000)
driver.get(Base_url)

html = driver.page_source
soup = BeautifulSoup(html, 'html.parser')

for div in soup.find_all('div', class_='news'):  
    a = div.findAll('a')   
    print(a['href'])

谢谢

最佳答案

您想要的内容位于框架内:

<iframe width="100%" frameborder="0" src="http://hindubusiness.cmlinks.com/Companydetails.aspx?&cocode=INE117A01022" id="compInfo" height="600px">...</iframe>

所以,首先您必须切换到该框架。您可以通过添加以下行来做到这一点:

driver.switch_to.default_content()
driver.switch_to.frame('compInfo')

完整代码(使其 headless ):

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

Base_url = "http://www.thehindubusinessline.com/stocks/abb-india-ltd/overview/"

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get(Base_url)
driver.switch_to.frame('compInfo')
soup = BeautifulSoup(driver.page_source, 'lxml')
for link in soup.select('.news a'):  
    print(link['href'])

输出:

/HomeFinancial.aspx?&cocode=INE117A01022&Cname=ABB-India-Ltd&srno=17040010444&opt=9
/HomeFinancial.aspx?&cocode=INE117A01022&Cname=ABB-India-Ltd&srno=17038039002&opt=9
/HomeFinancial.aspx?&cocode=INE117A01022&Cname=ABB-India-Ltd&srno=17019039003&opt=9
/HomeFinancial.aspx?&cocode=INE117A01022&Cname=ABB-India-Ltd&srno=17019038003&opt=9
/HomeFinancial.aspx?&cocode=INE117A01022&Cname=ABB-India-Ltd&srno=17019010085&opt=9

关于python - 使用 python -selenium 进行网页抓取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48717962/

相关文章:

c# - 无法使用 Selenium Webdriver 打开 chrome 浏览器。管理员禁止加载解压的扩展

python - find_next 未捕获所有 <div> 实例

python - 从Python中的列表列表中提取整数

python - 如果满足某些条件,则在组内将日期移动到上一年的同一日期

python - 将分组的 pandas DataFrame 转换为 3 维数组以进行序列预测

python - 使用 BeautifulSoup 提取特定标题下的文本

python-3.x - 如何将从维基百科表中抓取的数据转换为字典列表?

python - 使用 Python Pandas 使用通配符名称搜索对所有列求和

java - 无法使用 CSS 选择器在模式窗口中提取密码字段 - Selenium Java

selenium - 使用 Selenium WebDriver 模拟 ENTER 或 RETURN 的最佳实践是什么