我有这个html:
<div class="et_pb_text_inner">
<h3 style="text-align: center;"><i class="fal fa-ruler-combined"></i><br /> 1672 Square Feet</h3>
<p style="text-align: center;">
First Floor 1085 s.f.<br />
Second Floor 587 s.f.<br />
Porches 393 s.f.<br />
Covered Parking 642 s.f.<br />
Storage 187 s.f.<br />
Under Roof 2894 s.f.
</p>
</div>
我的 Xpath 代码是:
//div[@class='et_pb_text_inner']/p/text()
但它只给我第一个换行符之前的文本。
First Floor 1085 s.f.
有没有办法仅获取段落元素内的所有数据?有办法界定吗?
我想要一个这样的字符串:
First Floor 1085 s.f.<br />Second Floor 587 s.f.<br />Porches 393 s.f.<br />Covered Parking 642 s.f.<br />Storage 187 s.f.<br />Under Roof 2894 s.f.
所以之后我会尝试清理数据。
我是 xpath 表达式的新手。
预先感谢您的帮助。 =) 对我蹩脚的英语感到抱歉。 :P
我的.py代码是:
import requests
from lxml import html
resp = requests.get(
url="https://tyreehouseplans.com/shop/house-plans/beach-house-plans/crew-cut-house-plan/",
headers={'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'}
)
tree = html.fromstring(html=resp.text)
title = tree.xpath("//div[@class='et_pb_module_inner']/h1/text()")[0]
dimensions = tree.xpath("//div[@class='et_pb_text_inner']/p/text()")[0]
print(title)
print(dimensions)
最佳答案
text()
返回一个文本节点,<p>
tag包含6个这样的节点,所以需要删除索引[0]
。您还需要给出更准确的xpath
删除不需要的结果
dimensions = tree.xpath("//h3[contains(., '1672 Square Feet')]/following-sibling::p/text()")
将给出一个包含 6 个字符串的列表
['First Floor 1085 s.f.', '\nSecond Floor 587 s.f.', '\nPorches 393 s.f.', '\nCovered Parking 642 s.f.', '\nStorage 187 s.f.', '\nUnder Roof 2894 s.f.']
关于python - 用于获取 <p> 内所有数据的 Xpath 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195589/