【问题标题】:Scraping href title using lxml and XPath使用 lxml 和 XPath 抓取 href 标题
【发布时间】:2016-06-23 06:06:36
【问题描述】:
from lxml import html
import requests

for i in range(44,530):      # Number of pages plus one 
    url = "http://postscapes.com/companies/r/{}".format(i)
    page = requests.get(url)
    tree = html.fromstring(page.content)

contactemail = tree.xpath('//*[@id="rt-mainbody"]/div/div/div[2]/div[4]/address/a')

print contactemail

我正在尝试从公司目录的 900 个不同页面中抓取电子邮件。每个页面中的 HTML 代码都相对相似。但是,Contactemail 返回元素值。上面的 XPath 是下面代码的 href 值。 我想通过 XPath 从 href 值中提取 只是标题 contact@23-de-enero.com,但我不知道从哪里开始。 我也希望它适用于不同的页面,而不仅仅是这个 href 值/网页。

<a href="mailto:contact@23-de-enero.com">contact@23-de-enero.com</a>

我查看了正则表达式,并尝试使用 contactemail.textcontent() 进行打印,但它不起作用。

有什么建议吗?

【问题讨论】:

    标签: python regex xpath lxml


    【解决方案1】:

    有一些可能的方法可以提取相同的值,即电子邮件地址,例如:

    # get email address from inner text of the element :
    print contactemail[0].text
    
    # get email address from href attribute + substring-after() :
    print contactemail[0].xpath('substring-after(@href, "mailto:")')
    

    如果您在一个 address 父元素中可能有多个 a 元素,则可以使用列表解析语法:

    print [link.text for link in contactemail]
    

    【讨论】:

    • 嗨 har07,感谢您的回复。前两个返回索引错误,列表超出页面。最后一个有效,但它只返回 None。
    • 您的 XPath 似乎未能找到目标元素。抛出错误时 url 中的数字是多少?尝试将 XPath 简化为://*[@id="rt-mainbody"]//address/a
    • 我简化了 xpath。它仍然返回无。关于索引错误出现的数字,它从postscapes.com/companies/r/44 -> 一直到530。我尝试了其他几种技术for elt in contactemail: print(elt.text_content()),但它开始返回带有单词电子邮件保护的奇怪值。
    猜你喜欢
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多