python - Scrapy:选择所有子元素的文本,但也返回子 HTML
问题描述
我正在编写一个 Scrapy 蜘蛛来抓取这个页面,我只想要带有类的元素的文本jam_content
及其所有后代。所以理想情况下我应该得到
CYBERPUNK GAME JAM 2014
CLICK HERE!
这是我的选择器response.css(".jam_content *::text").extract()
:
它甚至返回孩子的 HTML
['\r\n\r\n\r\n',
'\r\n',
'CYBERPUNK GAME JAM 2014',
'\r\n',
'\r\n \r\n .game_grid .game_cell .game_title a {\r\n color: #029671;\r\n }\r\n \r\n .game_grid .game_cell .game_author a {\r\n color: #00aa99;\r\n }\r\n \r\n .game_grid .game_cell .game_genre {\r\n color: #c5007d;\r\n }\r\n \r\n .game_grid .game_cell .game_platform {\r\n color: #990088;\r\n }\r\n \r\n \r\n .add_game_btn {\r\n background-color: #029671;\r\n border: 4px solid #c5007d;\r\n box-shadow: 0 0 0 4px #380024;\r\n padding: 10px 15px;\r\n font-size: 18px;\r\n font-family: \'Lucida Console\';\r\n color: #00ffcc;\r\n cursor: pointer;\r\n} \r\n \r\n
.view_jam .grid_outer {\r\n border-top:0;\r\n border-bottom:0;\r\n background:#000; }\r\n \r\nbody {\r\n\tbackground-image: url(http://i.imgur.com/ReRqo6t.png);\r\n\tbackground-repeat: repeat-x;\r\n\tbackground-color: #000;\r\n}\r\nbody,td,th {\r\n\tcolor: #0FF;\r\n\tfont-family: "Lucida Console", Monaco, monospace;\r\n}\r\na:link {\r\n\tcolor: #C5007D;\r\n}\r\na:visited {\r\n\tcolor: #C5007D;\r\n}\r\na:hover {\r\n\tcolor: #C5007D;\r\n}\r\na:active {\r\n\tcolor: #C5007D;\r\n}\r\n.mag_not_link {\r\n\tcolor: #C5007D;\r\n\tfont-weight: bold;\r\n}\r\n',
'\r\n\r\n\r\n\r\n',
'\r\n ',
'\r\n ',
'CLICK HERE!',
'\r\n',
'\r\n\r\n']
我尝试了另一个response.xpath("./*[@class='jam_content']//text()")
,它什么也没返回
我该怎么做呢?
解决方案
更新您的选择器以不获取元素的内容style
:
response.css(".jam_content *:not(style)::text").extract()
然后你可以做一个列表理解,过滤掉空白文本的项目.strip()
:
my_text = [text for text in response.css(".jam_content *:not(style)::text").extract() if text.strip()]
这将返回:
['CYBERPUNK GAME JAM 2014', 'CLICK HERE!']
然后你可以简单地将它连接在一起:
print('\n'.join(my_text))
推荐阅读
- java - 在 Java 中从 pdf 文件中获取文本,而不使用默认 Java API 以外的任何库
- vue.js - 为什么这个函数除了@click 之外还能工作?
- matlab - 检测带有部分边缘的圆(用于微载体上的细胞生长的 MATLAB)
- acumatica - 使用 PXDatabase SelectMulti 进行表连接
- javascript - 需要通过 props 传递效果或从 preact/react 中的根组件外部强制组件重新加载
- amazon-web-services - 如何使用 IAM 从 EC2 连接到 AWS Elasticsearch?
- c# - 我试图简单地将两种不同的数据类型附加到我的 xml 文件中并再次读取它们,但出现错误
- excel - Vba for loop to repeat code output for cell rage
- javascript - 是否可以将表单输入设置为 0px 高度?
- python - Dask 数据帧计算失败