【发布时间】:2014-03-01 12:03:06
【问题描述】:
我正在使用 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&u=12563">port_new_cape</a></td>
<td class="position"><a href="./search.php?id=12563&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 </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打开本地文件好像不太合适。
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>
如何练习使用本地文件?
【问题讨论】:
-
请尝试:
soup = BeautifulSoup(open(url).read())并注意 url 应为url = r"C:\example.html"否则 url 中的 `\` 充当转义字符。 -
谢谢你,钱丹。我将其更改为 url = r"C:\example.html" page = open(url) soup = BeautifulSoup(page.read()),它可以工作。在我的情况下,“urllib2.url”在这里没用。
标签: python beautifulsoup