【问题标题】:Web scraping with python -selenium使用 python -selenium 进行网页抓取
【发布时间】:2018-07-20 22:33:34
【问题描述】:

我想从“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'])

谢谢

【问题讨论】:

  • 我认为您的问题是该页面没有任何带有新闻类的divs。它有 articles 和新闻类。
  • @jayant 你知道有什么方法可以刮掉所有这些href吗?我想要所有这些 href 内容(最新消息)

标签: python selenium web-scraping beautifulsoup


【解决方案1】:

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

<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')

完整的代码(使其无头):

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

【讨论】:

  • 我们可以隐藏那个 chrome 弹出窗口吗?
  • 是的,我们可以。搜索如何使用 chrome_options 添加参数。并使用--headless
  • 或者更好的是,使用 PhantomJS
  • 在选择任何无头浏览器的情况下,我认为 chrome 比 phantomjs 更好,因为在启动点击时,前者的问题比后者少。但是,上面的脚本现在可以无头运行@python。
  • 您面临的问题与路径相关,因此有两种选择:1. 创建一个描述您面临的障碍的新帖子并在此处放置链接 2. 或者,坚持您的方式首先。
【解决方案2】:

这样的事情会起作用:

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

【讨论】:

  • 我想要公司新闻中的href
猜你喜欢
  • 2021-05-08
  • 2020-03-13
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多