【问题标题】:Scrape right phone numbers using beautiful soup in python在 python 中使用漂亮的汤刮取正确的电话号码
【发布时间】:2019-05-02 18:03:52
【问题描述】:

我正在使用 python 3 和美丽的汤来抓取联系方式,例如电子邮件和电话号码,其中的 url 是在给定关键字的帮助下从谷歌搜索中找到的。

我已经从网址中正确地抓取了电子邮件,但我无法从网站上准确地抓取电话号码。

from bs4 import BeautifulSoup
import sys
import requests
import urllib.request
import pandas as pd
from urllib.request import urlopen,urlparse, Request,HTTPError
import re
import numpy as np
import csv
import json


def get_keyword(word):
try:     
from google search import search     
except ImportError:    
print("No module named 'google' found")   
# to search     
query = word    
url=[]    
for j in search (query, tld ="co.uk", num=10, stop=1, pause=2):    url.append(j)
return url, word
def scrape(req1, word):   
req2=req1
req1 = Request(req1, headers={'User-Agent': 'Mozilla/5.0 Chrome/24.0.1312.27 Safari/537.17 '})  
f = url open(req1)
s = f.read().decode('UTF-8') 
reg = "((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,3})|(\(?\d{2,3}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}"
phone = re. find all(reg, s)    
emails = re. find all(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,3}",s)  #Email regex    
ph=[]    
for i in phone:    
g  = list(filter(None, i))    
g=''.join(g)    
ph.append(g)    
def Remove(duplicate):     
final_list = []     
for num in duplicate:     
if num not in final_list:     
final_list.append(num)     
return final_list 
k = Remove(ph)    
df = pd.DataFrame(k, columns=['phone'])   
df2 = pd.DataFrame(emails, columns=['email'])    
df3 = pd.DataFrame([req2],columns=['url'])    
new_df = df.join([df3,df2])
return new_df

if __name__ == '__main__':
df_new = pd.DataFrame(columns = ['email','url','phone'])
x, y=get_keyword("women entrepreneur")#keyword
print(x)
for i in x:    
k = scrape(i, y) #i=links in the list of x which means list of url
df_new = pd.concat([df_new,k],ignore_index=True)

我想从网站上获取确切的电话号码,但实际上我得到了许多其他号码作为输出。示例(“电话”:“1761768436145”)不是准确的电话号码。如果没有找到号码,则应显示为“未找到电话号码”。

【问题讨论】:

  • 也许使用更简单的regexes
  • 您的代码中有随机空格。请更正它们。

标签: python-3.x web-scraping beautifulsoup


【解决方案1】:

匹配手机:

# https://stackoverflow.com/a/3868861/15164646
match_phone = re.findall(r'((?:\+\d{2}[-\.\s]??|\d{4}[-\.\s]??)?(?:\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}))', snippet)
phone = ''.join(match_phone)

匹配电子邮件:

match_email = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', snippet)
email = ''.join(match_email)

代码和full example in the online IDE

import requests, lxml, re
from bs4 import BeautifulSoup

headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582"
}

params = {
  'q': 'site:Facebook.com Dentist gmail.com',
  'hl': 'en',
  'gl': 'us'
}

html = requests.get(f'https://www.google.com/search',
                    headers=headers,
                    params=params).text
soup = BeautifulSoup(html, 'lxml')

for result in soup.findAll('div', class_='tF2Cxc'):
    title = result.select_one('.DKV0Md').text
    link = result.find('a')['href']
    snippet = result.select_one('.lyLwlc').text

    match_email = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', snippet)
    email = ''.join(match_email)

    match_phone = re.findall(r'((?:\+\d{2}[-\.\s]??|\d{4}[-\.\s]??)?(?:\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}))', snippet)
    phone = ''.join(match_phone)

    print(f'{title}\n{link}\n{snippet}\n{email}\n{phone}\n')

--------
'''
Allenwood Dental - Home | Facebook
https://m.facebook.com/Allenwood-Dental-103141398249324/
Get Directions. Rating · 0. (0 reviews). 5 people checked in here. (734) 294-6003. allenwooddental@gmail.com. https://allenwooddental.com/. Closed Now.
allenwooddental@gmail.com
(734) 294-6003
...
'''

或者,您可以使用来自 SerpApi 的 Google Organic Results API 来实现相同的目的。这是一个带有免费计划的付费 API。

主要区别在于,如果 HTML 中的某些内容会发生变化,或者您不想绕过 Google 的阻止,因为它已经为最终用户完成,您不必随着时间的推移维护解析器。真正需要做的就是迭代结构化的 JSON 并得到你想要的。

要集成的代码:

from serpapi import GoogleSearch
import os, json, re

params = {
  "engine": "google",
  "q": "site:Facebook.com Dentist gmail.com",
  "api_key": os.getenv('API_KEY')
}

search = GoogleSearch(params)
results = search.get_dict()

data = []

for result in results['organic_results']:
  title = result['title']
  link = result['link']
  snippet = result['snippet']

  match_email = re.findall(r'[\w\.-]+@[\w\.-]+\.\w+', snippet)
  email = '\n'.join(match_email)

  match_phone = re.findall(r'((?:\+\d{2}[-\.\s]??|\d{4}[-\.\s]??)?(?:\d{3}[-\.\s]??\d{3}[-\.\s]??\d{4}|\(\d{3}\)\s*\d{3}[-\.\s]??\d{4}|\d{3}[-\.\s]??\d{4}))', snippet)
  phone = ''.join(match_phone)

  print(f'{title}\n{link}\n{snippet}\n{email}\n{phone}\n')

--------
'''
Dental Professionals of Coral Springs - Posts | Facebook
https://www.facebook.com/DentalProfessionalsCoralSprings/posts
TELEDENTESTRY NOW AVAILABLE!!!!! GIVE USA CALL TO LEARN MORE !!! ☎️ 954-255-5858. Dpofcoralsprings@gmail.com.
Dpofcoralsprings@gmail.com
954-255-5858
...
'''

免责声明,我为 SerpApi 工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-22
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-14
    • 2017-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多