簡體   English   中英

使用Python和BeautifulSoup(將網頁源代碼保存到本地文件中)

[英]Using Python and BeautifulSoup (saved webpage source codes into a local file)

我使用的是 Python 2.7 + BeautifulSoup 4.3.2。

我正在嘗試使用 Python 和 BeautifulSoup 在網頁上獲取信息。 由於網頁在公司網站,需要登錄和重定向,我將目標頁面的源代碼頁復制到一個文件中,保存為“example.html”在C:\\,方便練習。

這是原始代碼的一部分:

<tr class="ghj">
    <td><span class="city-sh"><sh src="./citys/1.jpg" alt="boy" title="boy" /></span><a href="./membercity.php?mode=view&amp;u=12563">port_new_cape</a></td>
    <td class="position"><a href="./search.php?id=12563&amp;sr=positions" title="Search positions">452</a></td>
    <td class="details"><div>South</div></td>
    <td>May 09, 1997</td>
    <td>Jan 23, 2009 12:05 pm&nbsp;</td>
</tr>

到目前為止我制定的代碼是:

from bs4 import BeautifulSoup
import re
import urllib2

url = "C:\example.html"
page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())

cities = soup.find_all('span', {'class' : 'city-sh'})

for city in cities:
print city

這只是測試的第一階段,所以它有點不完整。

但是,當我運行它時,它給出了一條錯誤消息。 使用urllib2.urlopen打開本地文件似乎urllib2.urlopen

 Traceback (most recent call last):
   File "C:\Python27\Testing.py", line 8, in <module>
     page = urllib2.urlopen(url)
   File "C:\Python27\lib\urllib2.py", line 127, in urlopen
     return _opener.open(url, data, timeout)
   File "C:\Python27\lib\urllib2.py", line 404, in open
     response = self._open(req, data)
   File "C:\Python27\lib\urllib2.py", line 427, in _open
     'unknown_open', req)
   File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
     result = func(*args)
   File "C:\Python27\lib\urllib2.py", line 1247, in unknown_open
     raise URLError('unknown url type: %s' % type)
 URLError: <urlopen error unknown url type: c>

如何練習使用本地文件?

使用 BeautifulSoup 打開本地文件的最佳方法是直接將文件處理程序傳遞給它。 http://www.crummy.com/software/BeautifulSoup/bs4/doc/#making-the-soup

from bs4 import BeautifulSoup

with open("C:\\example.html") as fp:
    soup = BeautifulSoup(fp, 'html.parser')

for city in soup.find_all('span', {'class' : 'city-sh'}):
    print(city)

在昌丹的幫助下,問題得到了解決。 所有的功勞都歸他所有。 :)

“urllib2.url”在這里沒用。

from bs4 import BeautifulSoup
import re
# import urllib2

url = "C:\example.html"
page = open(url)
soup = BeautifulSoup(page.read())

cities = soup.find_all('span', {'class' : 'city-sh'})

for city in cities:
    print city

您也可以嘗試使用 lxml 解析器。 這是您的 html 數據示例。

from lxml.html import fromstring
import lxml.html as PARSER

data = open('example.html').read()
root = PARSER.fromstring(data)

for ele in root.getiterator():
    if ele.tag == "td":
        print ele.text_content()

o/p:port_new_cape 452 South 1997 年 5 月 9 日 2009 年 1 月 23 日下午 12:05

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM