取消使用lxml和XPath的href title

2024-04-27 04:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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值。 只想摘录联系邮箱:23-de-enero.com通过XPath从href值中获取,但我不知道从哪里开始。我还希望此功能适用于不同的页面,而不仅仅是此href value/webpage。

^{pr2}$

我研究过regex,并尝试用contactemail.textcontent()打印,但它不起作用。在

有什么提示吗?在


Tags: 代码fromimportdivcomtreeurlhtml
1条回答
网友
1楼 · 发布于 2024-04-27 04:51:07

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

# 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元素,则可以使用列表理解语法:

^{pr2}$

相关问题 更多 >