我有这段代码
site = hxs.select("//h1[@class='state']")
log.msg(str(site[0].extract()),level=log.ERROR)
输出
[scrapy] ERROR: <h1 class="state"><strong>
1</strong>
<span> job containing <strong>php</strong> in <strong>region</strong> paying <strong>$30-40k per year</strong></span>
</h1>
是否可以只获取没有任何html标签的文本
答案 0 :(得分:49)
//h1[@class='state']
在您的上述xpath中,您选择的h1
代码具有class
属性state
这就是为什么它会选择h1 element
如果您只想选择h1
标签的文字,那么您只需
//h1[@class='state']/text()
如果您要选择h1
标签的文字及其子标签,则必须使用
//h1[@class='state']//text()
因此特定标记文本的差异为/text()
,特定标记及其子标记的文本为//text()
下面提到的代码适合你
site = ''.join(hxs.select("//h1[@class='state']/text()").extract()).strip()
答案 1 :(得分:4)
您可以使用BeautifulSoup get_text()
功能。
from bs4 import BeautifulSoup
text = '''
<td><a href="http://www.fakewebsite.com">Please can you strip me?</a>
<br/><a href="http://www.fakewebsite.com">I am waiting....</a>
</td>
'''
soup = BeautifulSoup(text)
print(soup.get_text())
答案 2 :(得分:1)
我没有运行scrapy实例,所以我无法测试它;但您可以尝试在搜索表达式中使用text()
。
例如:
site = hxs.select("//h1[@class='state']/text()")
(从tutorial
获得)
答案 3 :(得分:1)
您可以使用BeautifulSoup来删除html标记,以下是一个示例:
from BeautifulSoup import BeautifulSoup
''.join(BeautifulSoup(str(site[0].extract())).findAll(text=True))
然后您可以删除所有其他空格,新行等。
如果您不想使用其他模块,可以尝试使用简单的正则表达式:
# replace html tags with ' '
text = re.sub(r'<[^>]*?>', ' ', str(site[0].extract()))
答案 4 :(得分:0)
您可以使用html2text
import html2text
converter = html2text.HTML2Text()
print converter.handle("<div>Please!!!<span>remove me</span></div>")