【发布时间】:2021-01-09 09:54:28
【问题描述】:
我是 Scrapy 的新手。我正在尝试从以下 URL 中提取 h2 文本:'https://www.tysonprop.co.za/agents/'
我有两个问题:
-
我的 xpath 可以到达 script 元素,但在 script 标签内找不到 h2 或 div 元素。我什至尝试将 HTML 文件保存到我的机器并抓取该文件,但同样的问题发生了。我已经三次检查了我的 xpath 代码,一切似乎都井井有条。
-
当网站显示在我的浏览器中时,branch.branch_name 解析为“Tysen Properties Head Office”。如何获取值(即“Tysen Properties Head Office”)而不是变量名(branch.branch_name)?
我的 Python 代码:
import scrapy
class TysonSpider(scrapy.Spider):
name = 'tyson_spider'
def start_requests(self):
url = 'https://www.tysonprop.co.za/agents/'
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
script = response.xpath('//script[@id="id_branch_template"]')
div = script.xpath('./div[contains(@class,"branch-container")]')
h2 = div.xpath('/h2[contains(@class,"branch-name")]/text()').extract()
yield {'branchName': h2}
HTML 摘录如下:
<script type="text/html" id="id_branch_template">
<div id="branch-<%= branch.id %>" class="clearfix margin-top30 branch-container" style="display: none;">
<h2 class="grid_12 branch-name margin-bottom20"><%= branch.branch_name %></h2>
<div class="branch-agents container_12 first last clearfix">
<div id="agents-list-left" class="agents-list left grid_6">
</div>
<div id="agents-list-right" class="agents-list right grid_6">
</div>
</div>
</div>
</script>
【问题讨论】:
-
HTML 代码为:script type="text/html" id="id_branch_template">
标签: javascript python html scrapy