Python 使用 Selenium 和 Beautiful Soup 抓取 JavaScript

标签 python selenium screen-scraping beautifulsoup

我正在尝试使用 BS 和 Selenium 抓取启用 JavaScript 的页面。 到目前为止,我有以下代码。它仍然没有以某种方式检测到 JavaScript(并返回空值)。在这种情况下,我试图在底部抓取 Facebook 评论。 (检查元素将类显示为 postText)
感谢您的帮助!

from selenium import webdriver  
from selenium.common.exceptions import NoSuchElementException  
from selenium.webdriver.common.keys import Keys  
import BeautifulSoup

browser = webdriver.Firefox()  
browser.get('http://techcrunch.com/2012/05/15/facebook-lightbox/')  
html_source = browser.page_source  
browser.quit()

soup = BeautifulSoup.BeautifulSoup(html_source)  
comments = soup("div", {"class":"postText"})  
print comments

最佳答案

下面修复了您的代码中的一些错误。但是,“postText”类必须存在于其他地方,因为它没有在原始源代码中定义。 我修改后的代码版本已经过测试,可以在多个网站上运行。

from selenium import webdriver  
from selenium.common.exceptions import NoSuchElementException  
from selenium.webdriver.common.keys import Keys  
from bs4 import BeautifulSoup

browser = webdriver.Firefox()  
browser.get('http://techcrunch.com/2012/05/15/facebook-lightbox/')  
html_source = browser.page_source  
browser.quit()

soup = BeautifulSoup(html_source,'html.parser')  
#class "postText" is not defined in the source code
comments = soup.findAll('div',{'class':'postText'})  
print comments

关于Python 使用 Selenium 和 Beautiful Soup 抓取 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14529849/

相关文章:

java - 查找具有完全相同属性的元素

selenium - 使用 gulp 运行 Protractor 和 selenium 时出现问题

python - 将三个 Pandas 数据框合二为一?

java - 安装 Selenium RC Java 客户端驱动程序时出现问题

python - 没有 CUDA 的 PyTorch torch_sparse 安装

python - 使用 BS4 python 进行抓取

python - 使用美汤蟒刮痧

Python 抓取 Html 的问题

python - 对于不规则的分隔符,如何使 pandas read_csv 中的分隔符更加灵活 wrt 空格?

python - Python中的线程本地存储