使用 lxml 和 XPath 抓取 href 标题
Scraping href title using lxml and XPath
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 returns 元素值 。上面的 XPath 是下面代码的 href 值。
我想通过 XPath 从 href 值中提取 just the title contact@23-de-enero.com,但我不知道不知道从哪里开始。 我也希望它适用于不同的页面,而不仅仅是这个 href 值/网页。
<a href="mailto:contact@23-de-enero.com">contact@23-de-enero.com</a>
我查看了正则表达式,并尝试使用 contactemail.textcontent()
进行打印,但它不起作用。
有什么建议吗?
有一些可能的方法可以提取相同的值,即电子邮件地址,例如:
# 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]
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 returns 元素值 。上面的 XPath 是下面代码的 href 值。 我想通过 XPath 从 href 值中提取 just the title contact@23-de-enero.com,但我不知道不知道从哪里开始。 我也希望它适用于不同的页面,而不仅仅是这个 href 值/网页。
<a href="mailto:contact@23-de-enero.com">contact@23-de-enero.com</a>
我查看了正则表达式,并尝试使用 contactemail.textcontent()
进行打印,但它不起作用。
有什么建议吗?
有一些可能的方法可以提取相同的值,即电子邮件地址,例如:
# 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]