我需要抓取嵌套在HTML页面中的这部分文本。
link: http://warframe.wikia.com/wiki/Frost
text needed: Frost's component blueprints are acquired from Lieutenant Lech Kril & Captain Vor (Exta, Ceres).
我以前用过bs4,但我不知道如何提取这个特定的文本。
发布于 2018-08-05 04:09:58
此页面对web抓取不是很友好。我创建了一个带有两个参数tag_from
和tag_to
的函数get_text()
。它将抓取这两个标记之间的所有文本:
from bs4 import BeautifulSoup, NavigableString
import requests
soup = BeautifulSoup(requests.get('http://warframe.wikia.com/wiki/Frost').text, 'lxml')
def get_text(tag_from, tag_to):
rv = ''
while True:
s = tag_from.next_sibling
if s == tag_to:
break
if isinstance(s, NavigableString):
rv += s
else:
rv += s.text
tag_from = tag_from.next_sibling
return rv.strip()
s = get_text(soup.select_one('#Acquisition').parent, soup.select_one('#Acquisition').parent.find_next('table'))
print(s)
打印:
Frost's component blueprints are acquired from Lieutenant Lech Kril & Captain Vor (Exta, Ceres).
编辑:
在这个页面上,这个文本不容易被定位,没有封装它的标签。所以我的方法是从一个标记开始,从我找到的所有内容构建字符串,直到结束标记。
一些内容是NavigableString
(纯文本)类型,一些内容是其他标记(我用.text
属性从这些标记中获得字符串)。
https://stackoverflow.com/questions/51688712
复制相似问题