爬取电子邮件地址通常涉及以下步骤:
发送HTTP请求:
使用`requests`库发送HTTP请求以获取网页内容。
解析网页内容:
使用`BeautifulSoup`或`lxml`解析网页内容。
提取电子邮件地址:
使用正则表达式从网页内容中提取电子邮件地址。
```python
from bs4 import BeautifulSoup
import requests
import re
def extract_emails_from_url(url):
发送HTTP请求获取网页内容
response = requests.get(url)
html_content = response.text
使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html_content, 'lxml')
定义电子邮件的正则表达式
email_pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
使用正则表达式在网页内容中查找所有电子邮件地址
emails = re.findall(email_pattern, soup.get_text())
return emails
示例使用
url = 'http://example.com' 替换为要爬取的网页URL
emails = extract_emails_from_url(url)
print(emails)
请注意,在爬取网站时,应遵守网站的`robots.txt`文件规定,并尊重网站的版权和使用条款。此外,频繁的请求可能会给网站服务器带来负担,因此请合理控制爬取频率。