Python web-scraping 更改 href

Python web-scraping with changing href

我一直在使用 Python 2.7

抓取一些网站
    page = requests.get(URL)
    tree = html.fromstring(page.content)

    prices = tree.xpath('//span[@class="product-price"]/text()')
    titles = tree.xpath('//span[@class="product-title"]/text()')

这对于带有这些清晰标签的网站来说效果很好,但我遇到的很多网站都有以下 HTML 设置:

<a href="https://www.retronintendokopen.nl/gameboy/games/gameboy-classic/populous" class="product-name"><strong>Populous</strong></a>

(我很想摘取标题:Populous) 在我提取的每个标题的 href 发生变化的地方,我已经针对上面的示例尝试了以下操作,希望它能看到 class 并且这就足够了,但这不起作用

titles = tree.xpath('//a[@class="product-name"]/text()')

我正在寻找一个可以像 * 一样工作的字符,例如“我不在乎这里有什么,只要把所有东西都带上 href=.. 但找不到任何东西

titles = tree.xpath('//a[@href="*"]/text()')

此外,我是否需要指定在 a 标签中也有 class=,例如

titles = tree.xpath('//a[@href="*" @class="product-name"]/text()')

编辑:如果使用

的路径中只有更改标签,我也找到了修复方法
titles = tree.xpath('//h3/a/@title')

此标签的示例

<h3><a href="http://www.a-retrogame.nl/index.php?id_product=5843&amp;controller=product&amp;id_lang=7" title="4 in 1 fun pack">4 in 1 fun pack</a></h3>

试试这个:

titles = tree.xpath('//a[@class="product-name"]//text()')

注意 // 在 class 选择器之后。