【发布时间】:2017-03-06 05:54:12
【问题描述】:
我编写了一个基本脚本来从网页中提取电子邮件。
from bs4 import BeautifulSoup
import requests, re
def get_email(url):
response = requests.get(url, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.107 Safari/537.36',
'Upgrade-Insecure-Requests': '1', 'x-runtime': '148ms'}, allow_redirects=True).content
soup = BeautifulSoup(response, "html.parser")
email = soup(text=re.compile(r'^[a-zA-Z]+[\w\-.]+@[\w-]+\.[\w.-]+[a-zA-Z]')) # this is working with
print ("email ",email)
get_email('http://www.aberdeenweddingshop.co.uk/contact-us')
get_email('http://www.foodforthoughtdeli.co.uk/contact.htm')
OUTPUT:
email info@aberdeenweddingshop.co.uk
email [] <------------------------#should give info@foodforthoughtdeli.co.uk
它为第一个 URL 提供了正确的结果,但没有在第二个 URL 中获取任何内容。我不知道原因。我也尝试更改正则表达式。我验证了正则表达式here,但由于某种原因它不能在代码中工作。
【问题讨论】:
标签: regex python-3.x beautifulsoup