【问题标题】:Scraping a site using Selenium and BeautifulSoup使用 Selenium 和 BeautifulSoup 抓取网站
【发布时间】:2015-12-10 20:13:00
【问题描述】:

所以我正在尝试抓取一个使用 JS 动态加载内容的网站。我的目标是构建一个快速的 python 脚本来加载一个站点,看看是否有某个词,如果它在那里,然后给我发电子邮件。

我对编码比较陌生,所以如果有更好的方法,我很乐意听到。

我目前正在使用 Selenium 加载页面,然后使用 BeautifulSoup 抓取生成的页面,这就是我遇到问题的地方。我如何让 beautifulsoup 刮掉我刚刚在 selenium 中打开的网站?

from __future__ import print_function
from bs4 import BeautifulSoup
from selenium import webdriver
import requests
import urllib, urllib2
import time


url = 'http://www.somesite.com/'

path_to_chromedriver = '/Users/admin/Downloads/chromedriver'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)

site = browser.get(url)

html = urllib.urlopen(site).read()
soup = BeautifulSoup(html, "lxml")
print(soup.prettify())

我有一个错误提示

Traceback (most recent call last):
  File "probation color.py", line 16, in <module>
    html = urllib.urlopen(site).read()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 87, in urlopen
    return opener.open(url)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 185, in open
    fullurl = unwrap(toBytes(fullurl))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 1075, in unwrap
    url = url.strip()
AttributeError: 'NoneType' object has no attribute 'strip'

我真的不明白或不明白为什么会发生。它是 urllib 内部的东西吗?我如何解决它?我认为解决这个问题会解决我的问题。

【问题讨论】:

    标签: javascript python selenium beautifulsoup


    【解决方案1】:

    可以使用浏览器上的“page_source”属性找到 HTML。这应该有效:

    browser = webdriver.Chrome(executable_path = path_to_chromedriver)
    browser.get(url)
    
    html = browser.page_source
    soup = BeautifulSoup(html, "lxml")
    print(soup.prettify())
    

    【讨论】:

    • 谢谢!正是我需要的。
    【解决方案2】:
    from __future__ import print_function
    from bs4 import BeautifulSoup
    from selenium import webdriver
    import requests
    #import urllib, urllib2
    import time
    
    
    url = 'http://www.somesite.com/'
    
    path_to_chromedriver = '/Users/admin/Downloads/chromedriver'
    browser = webdriver.Chrome(executable_path = path_to_chromedriver)
    
    site = browser.get(url)
    html = site.page_source #you should have used this...
    
    #html = urllib.urlopen(site).read() #this is the mistake u did...
    soup = BeautifulSoup(html, "lxml")
    print(soup.prettify())
    

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 1970-01-01
      • 2018-05-31
      • 2019-12-15
      • 2016-08-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多