我在xpath中使用python,并且在xpath语法中迷失了方向。我想要做的是检查html页面中的表中是否有标记。所以我使用xpath来完成这个任务。然后,如果没有此标记,则执行相对于该节的xpath搜索。我好像有些东西起作用了,但它起了相反的作用,我不知道为什么。示例代码如下。
main_sections = tree.xpath('//td[@class="cars"]')
for i in range(0, len(main_sections)):
has_no_flag = True
for c in main_sections[i].getchildren():
if c.tag == "span" and c.get("class") == "colorRed":
has_no_flag = False
if has_no_flag:
price = main_sections[i].xpath('//td[@class="cars"]/following-sibling::td[@class="price"]/span[@class="amount-value"]')
price_str = price[0].text.strip()我不认为xpath的价格是正确的。希望有人能启发我:)
发布于 2016-03-28 11:09:08
我不认为你在这里使用XPath是正确的。
只需过滤您希望拥有的节点,并丢弃您自己的循环和标志即可。
cars_without_tag_price = '''//td[
@class="cars" and not(span[@class="colorRed"])
]/following-sibling::td[@class="price"]/span[@class="amount-value"]
'''
for price_node in tree.xpath(cars_without_tag_price):
price_str = price_node.text.strip()https://stackoverflow.com/questions/36260599
复制相似问题