【发布时间】:2021-02-22 17:33:54
【问题描述】:
好吧,我有以下 html,我想从中获取 @data-coords 属性,但我希望纬度和经度位于不同的变量中。见下面的html:
<div id="gmap-container">
<div id="gmap-value" data-coords="-26.995548880319042,-48.633818457672135,16,150">
...
</div>
</div>
如果我使用 //div[@id='gmap-imovel']/@data-coords 作为 XPath,它会从 @data-coords 属性返回整个内容。
我的 Python 代码是这样的:
xpaths = {
"parser_lat": "//div[@id='gmap-value']/@data-coords",
"parser_lon": "//div[@id='gmap-value']/@data-coords"
}
latitude: str = parsel.Selector().xpath(xpaths['parser_lat']).extract_first()
longitude: str = parsel.Selector().xpath(xpaths['parser_lon']).extract_first()
return latitude, longitude
我想像上面提到的那样拆分纬度和经度,我知道我可以在 Python 代码中添加正则表达式来得到我想要的,但那样会破坏其他网站的管道。使用我不想使用的正则表达式的示例:
regex_expression = r'^-(\d+\.\d+)'
latitude = re.findall(regex_expression, '-26.995548880319042,-48.633818457672135,16,150')[0]
longitude = re.findall(regex_expression, '-26.995548880319042,-48.633818457672135,16,150')[1]
上面的这个例子会给我-26.995548880319042和-48.633818457672135各自的变量,但正如我所提到的,这会破坏到其他网站的管道。
我想只使用 XPath 得到我上面提到的这个结果,像这样:
parser_lat: regex('^-(\d+\.\d+)', //div[@id='gmap-imovel']/@data-coords)[0]
parser_lon: regex('^-(\d+\.\d+)', //div[@id='gmap-imovel']/@data-coords)[1]
然后在我给出的第一个 Python 代码示例中使用它。
我尝试使用 substring,但没有为我工作。
【问题讨论】:
-
“不更改我的代码”是什么意思?显然,您必须更改 something 来修复它。您能否编辑您的问题,包括使用的完整代码并指出可以更改和不能更改的部分?
-
我刚刚编辑了这个问题,更详细地思考了我想要什么,希望你能理解。我的完整代码太大了这里就不贴了,但是第一个代码示例基本一样。如果您想更好地查看它,我将在此处发布我的 GitHub 存储库。存储库:github.com/jakoritarleite/datareal-crawler 你想看的部分代码在
lib/models/crawl.py的_Scrape类中。