我正在尝试使用 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/