1

我正在学习如何使用 lxml/BeautifulSoup,我想知道如何尽可能方便地做到这一点。源代码的主体结构如下:

<p class = "info">
    <!-- a bunch of other tags and text in each paragraph class -->
</p>
<p class = "filler1">
</p>
<p class = "filler2">
</p>
<p class = "filler2">
</p>
<p class = "repeat">
</p>
<p class = "repeat">
</p>
<p class = "descr">
</p>
<p class = "descr">
</p>
<p class = "descr">
</p>

目前我只是在使用

soup = BeautifulSoup(open('savedPage.html'))
soup.body(text=True)

刮掉正文中的所有文本。我想知道是否有一种快速、方便的方法来:1)刮掉“filler2”之后段落类中的所有文本,2)避免转义序列

关于2),我知道我可以通过迭代来绕过这个问题

for i in range(1,len(soup.body(text=True))+1):
    soup.body(text=True)[i]

这将解释所有转义序列。但是,对于 1),有没有办法在“filler2”类之后抓取所有文本,仍然保持代码简单?不想遍历整个树或编写正则表达式。

4

1 回答 1

0

您可以尝试这样的事情 - 假设您正在尝试从正文中获取大部分文本。

data = urllib2.urlopen(link)
content = data.read()
# replace the script and style tags with html comments, so the bs4 just skips them
content = content.replace("<script", "<!--")
content = content.replace("</script>", "-->")
content = content.replace("<style", "<!--")
content = content.replace("</style>", "-->")
soup = BeautifulSoup(content, "lxml") # assuming you've imported lxml and bs4
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
Comments = [comment.extract() for comment in comments] # remove the commenys
words = []
for i in soup.stripped_strings:
    print i
# i will print most of the text of the page line by line

好吧,这种方法不是最干净的。但它应该可以正常工作。

于 2012-11-18T07:52:41.263 回答