要从 Google 搜索结果中删除电子邮件,您需要使用 regex
# this regex needs possible modifications
re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', variable_where_to_search_from)
代码:
from bs4 import BeautifulSoup
import requests, lxml, re
headers = {
"User-agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
"Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
html = requests.get('https://www.google.com/search?q="computer science ""usa" "@yahoo.com"', headers=headers)
soup = BeautifulSoup(html.text, 'lxml')
for result in soup.select('.tF2Cxc'):
try:
snippet = result.select_one('.lyLwlc').text
except:
snippet = None
match_email = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', str(snippet))
email = '\n'.join(match_email).strip()
print(email)
----------
'''
ahmed_733@yahoo.com
yjzou@uguam.uog
yzou2002@yahoo.com
...
或者,您可以使用来自 SerpApi 的 Google Organic Results API 来做同样的事情。这是一个带有免费计划的付费 API。
它不会使用正则表达式提取电子邮件,尽管它可能是一个很棒的功能。主要区别在于完成工作比从头开始创建一切都更容易、更快捷。
要集成的代码:
from serpapi import GoogleSearch
import re
params = {
"api_key": "YOUR_API_KEY",
"engine": "google",
"q": '"computer science ""usa" "@yahoo.com"',
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results['organic_results']:
try:
snippet = result['snippet']
except:
snippet = None
match_email = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', str(snippet))
email = '\n'.join(match_email).strip()
print(email)
---------
'''
shaikotweb@yahoo.com
ahmed_733@yahoo.com
RPeterson@L1id.com
rj_peterson@yahoo.com
'''
免责声明,我为 SerpApi 工作。