如何在python中使用Selenium和Beautifulsoup解析网站?

2024-04-30 04:36:09 发布

您现在位置:Python中文网/ 问答频道 /正文

刚开始编程,就知道如何使用Selenium导航到需要去的地方。我现在想分析数据,但不知道从哪里开始。有人能牵着我的手指点我正确的方向吗?

感谢任何帮助-


Tags: 数据selenium编程地方方向手指
3条回答

假设您在要解析的页面上,Selenium将源HTML存储在驱动程序的page_source属性中。然后将page_source加载到BeautifulSoup中,如下所示:

In [8]: from bs4 import BeautifulSoup

In [9]: from selenium import webdriver

In [10]: driver = webdriver.Firefox()

In [11]: driver.get('http://news.ycombinator.com')

In [12]: html = driver.page_source

In [13]: soup = BeautifulSoup(html)

In [14]: for tag in soup.find_all('title'):
   ....:     print tag.text
   ....:     
   ....:     
Hacker News

你确定要用硒吗?出于这个原因,我使用了PyQt4,它非常强大,你可以做任何你想做的事情。

我可以给你一个我刚刚写的示例代码,只要更改url,你就可以:

#! /usr/bin/env python2.7

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
from bs4 import BeautifulSoup
import sys, signal

class Browser(QWebView):
    def __init__(self):
        QWebView.__init__(self)
        self.loadProgress.connect(self._progress)
        self.loadFinished.connect(self._loadFinished)
        self.frame = self.page().currentFrame()

    def _progress(self, progress):
        print str(progress) + "%"

    def _loadFinished(self):
        print "Load Finished"
        html = unicode(self.frame.toHtml()).encode('utf-8')
        soup = BeautifulSoup(html)
        print soup.prettify()
        self.close()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    br = Browser()
    url = QUrl('http://web site that can contain javascript.com')
    br.load(url)
    br.show()
    if signal.signal(signal.SIGINT, signal.SIG_DFL):
        sys.exit(app.exec_())
    app.exec_()

由于你的问题不是特别具体,这里有一个简单的例子。要做更有用的事情,请阅读BSdocs。您还可以在SO中找到大量使用硒(和BS)的示例。

from selenium import webdriver
from bs4 import BeautifulSoup

browser=webdriver.Firefox()
browser.get('http://webpage.com')

soup=BeautifulSoup(browser.page_source)

#do something useful
#prints all the links with corresponding text

for link in soup.find_all('a'):
    print link.get('href',None),link.get_text()

相关问题 更多 >