相关疑难解决方法(0)

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

我使用的是Python 2.7 + BeautifulSoup 4.3.2.

我正在尝试使用Python和BeautifulSoup来获取网页上的信息.由于网页在公司网站上需要登录和重定向,因此我将目标网页的源代码复制到文件中,并将其保存为C:\中的"example.html",以方便练习.

这是原始代码的一部分:

<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>
Run Code Online (Sandbox Code Playgroud)

到目前为止我编写的代码是:

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
Run Code Online (Sandbox Code Playgroud)

这只是测试的第一阶段,有些没有完成.

但是,当我运行它时,它会显示错误消息,使用"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", …
Run Code Online (Sandbox Code Playgroud)

python beautifulsoup

41
推荐指数
3
解决办法
7万
查看次数

标签 统计

beautifulsoup ×1

python ×1