我看到很多Xpath答案,但没有CSS答案。我已经成功地提取了我需要的所有文本 - 但它完全"包装"了?在标签、字体详细信息等中。我正在从这个网站上提取一些角色描述。
我使用的代码改编自 Scrapy 教程 - 我想从每个角色的站点中提取所有与工作相关的文本:
def parse(self, response):
for href in response.css('.mask-on-hover + a::attr(href)'):
yield response.follow(href, self.parse_author)
def parse_author(self, response):
def extract_with_css(query):
return response.css(query).extract()
yield {
'role': extract_with_css('h1::text'),
'literature': extract_with_css('h3 span.info::text'),
'date-posted': extract_with_css('h3 span#ctl00_spListed.info.listed::text'),
'role-description': extract_with_css('#ctl00_regionContent_lblJobDescription span , strong::text'),}
我在特定页面的结果包括所有文本,还包括 html 标签和元素,包括跨度、样式、字体大小。
如何使用 CSS 按网站出现的顺序获取干净的文本?理想情况下,我想保留段落样式并最终将其发送到Excel/CSV中的一个单元格。
谢谢!
如果 css 选择器正是您想要的,您可以使用 w3lib 中的 remove_tags 方法,但我认为在您的情况下没有必要,请尝试以下操作:
'role-description': extract_with_css('#ctl00_regionContent_lblJobDescription span *::text')