使用Python和BeautifulSoup(将网页源代码保存到本地文件中)

80

我正在使用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 来打开本地文件。

 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>

我该如何练习使用本地文件?


9
请尝试使用代码soup = BeautifulSoup(open(url).read()),请注意url必须为url = r"C:\example.html",否则在url中的\将被视为转义字符。 - Chandan
2
谢谢,Chandan。我把它改成了url = r"C:\example.html",page = open(url),soup = BeautifulSoup(page.read()),现在它可以工作了。在我的情况下,“urllib2.url”是无用的。 - Mark K
3个回答

134

1
它显示了警告。答案在这里 - JustCurious
5
在Mac上,soup = BeautifulSoup(open("/path/to/your/file.html"), "html.parser")的意思是使用BeautifulSoup库将指定路径下的HTML文件解析为一个对象,并把它赋值给变量soup - Adrian
1
最佳方式?它显示ResourceWarning:未关闭的文件。 - Matej J
@MatejJ 感谢你的提醒。看起来他们更新了文档/工作方式。现在它不会自动为您处理关闭。已更新以匹配新的文档,使用上下文管理器。 - CasualDemon

42

在 Chandan 的帮助下,问题已经得到解决。所有的功劳都应归给他。 :)

"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

3
如果 urllib2.url 是无用的,那么你还需要 import urllib2 吗? - Zonker.in.Geneva
1
我会将 .soup = BeautifulSoup(page.read()) 替换为 .soup = BeautifulSoup(page.read(), features="lxml"),以便能够正确地浏览 DOM。 - Haddock-san
1
@Haddock-san,我在https://dev59.com/dj0DtIcB2Jgan1znrUIe上发现了最新的研究结果,你可能想要看一下。 - Mark K

6
您可以尝试使用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: 端口:新岬 452 南方 1997年5月9日 2009年1月23日下午12:05


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接