【发布时间】:2014-11-11 00:14:48
【问题描述】:
我正在尝试使用 BeautifulSoup 和 Python 从维基百科的表格中提取电视剧集的标题。 为了解释我到目前为止所做的事情,我使用了两个表:
1:http://en.wikipedia.org/wiki/Community_(season_1)
2:http://en.wikipedia.org/wiki/Two_and_a_Half_Men_(season_1)
现在,在表格中,每一集都包含在<td class="summary"> 中。
在第一个表中,<td> 也有一个<a>TitleName</a>,我可以使用以下代码很好地提取数据:
import urllib
import urllib2
from bs4 import BeautifulSoup
url = "http://en.wikipedia.org/wiki/Community_(season_1)"
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
for names in soup.select('td[class="summary"] > a'):
print names.string
但问题出现在第二张桌子上,即两个半男人,其中标题在 <td> 内
我使用这段代码来提取它们:
import urllib
import urllib2
from bs4 import BeautifulSoup
url = "http://en.wikipedia.org/wiki/Two_and_a_Half_Men_(season_1)"
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
for lel in soup.select('td[class="summary"]'):
print lel.string
但瓷砖带有引号,即“”。
我猜想删除引号会很容易,但是如果在一张表中,一些<td> 包含<a> 而有些不包含呢?如何让 python 决定它是否应该检查 <a> 元素?
如果在第一个代码块中,我删除了 > a ,那么我将得到 none 作为输出,因为父级和子级都包含字符串。如果我继续使用 names.strings 我得到 p>
<generator object _all_strings at 0x01B1CDA0>
如果我使用soup.get_text(),我会得到
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position 6818, character maps to <undefined>
请帮忙:)
【问题讨论】:
-
另一个建议:不要解析维基百科页面,而是解析来自 TVRage 的 xml:services.tvrage.com/feeds/full_show_info.php?sid=22589 用于社区,services.tvrage.com/feeds/full_show_info.php?sid=6454 用于 2½ Men
标签: python web-scraping beautifulsoup html-table wikipedia