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

Mar*_*k K 41 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", 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>
Run Code Online (Sandbox Code Playgroud)

我可以通过本地文件以何种方式练习?

Cas*_*mon 72

使用BeautifulSoup打开本地文件的最佳方法是直接将它传递给一个打开的文件处理程序.http://www.crummy.com/software/BeautifulSoup/bs4/doc/#making-the-soup

from bs4 import BeautifulSoup

soup = BeautifulSoup(open("C:\\example.html"), "html.parser")

for city in soup.find_all('span', {'class' : 'city-sh'}):
    print(city)
Run Code Online (Sandbox Code Playgroud)

  • 在 Mac 上,`soup = BeautifulSoup(open("/path/to/your/file.html"), "html.parser")` (3认同)

Mar*_*k K 21

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

  • 如果 `urllib2.url` 没用,那么还需要 `import urllib2` 吗? (3认同)

Tan*_*lam 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()
Run Code Online (Sandbox Code Playgroud)

o/p:port_new_cape 452 South May 09,1997 Jan 23,2009 12:05 pm