【发布时间】:2015-02-04 02:04:42
【问题描述】:
我有一个原始 html 字符串,我想将其转换为 scrapy HTML 响应对象,以便可以使用选择器 css 和 xpath,类似于 scrapy 的 response。我该怎么做?
【问题讨论】:
标签: python web-scraping scrapy
我有一个原始 html 字符串,我想将其转换为 scrapy HTML 响应对象,以便可以使用选择器 css 和 xpath,类似于 scrapy 的 response。我该怎么做?
【问题讨论】:
标签: python web-scraping scrapy
首先,如果是调试或测试目的,可以使用Scrapy shell:
$ cat index.html
<div id="test">
Test text
</div>
$ scrapy shell index.html
>>> response.xpath('//div[@id="test"]/text()').extract()[0].strip()
u'Test text'
会话期间有different objects available in the shell,如response和request。
或者,您可以实例化 HtmlResponse class 并在 body 中提供 HTML 字符串:
>>> from scrapy.http import HtmlResponse
>>> response = HtmlResponse(url="my HTML string", body='<div id="test">Test text</div>', encoding='utf-8')
>>> response.xpath('//div[@id="test"]/text()').extract()[0].strip()
u'Test text'
【讨论】:
Selector,请参阅 stackoverflow.com/questions/18836286/… 和 stackoverflow.com/questions/17975471/…。可能有帮助。谢谢。
scrapyjs 可能值得一试——也许你可以避免使用selenium。
您可以导入原生的scrapy选择器Selector并将html字符串声明为要解析的文本arg。
from scrapy.selector import Selector
def get_list_text_from_html_string(html_string):
html_item = Selector(text=html_string)
elements = [_li.get() for _li in html_item.css('ul > li::text')]
return elements
list_html_string = '<ul class="teams">\n<li>Bayern M.</li>\n<li>Palmeiras</li>\n<li>Liverpool</li>\n<li>Flamengo</li></ul>'
print(get_list_text_from_html_string(list_html_string))
>>> ['Bayern M.', 'Tigres', 'Liverpool', 'Flamengo']
【讨论】: