网页抓取手机号(《爬取》第2季第16集爬取函数 )
优采云 发布时间: 2021-09-26 22:04网页抓取手机号(《爬取》第2季第16集爬取函数
)
上次学爬图,这次想尝试爬取商家的联系电话。当然,这纯粹是个人技术研究。爬取后会及时删除,不得用于其他非法用途。所有后果由您自担风险。
首先,我在学习时使用了114个黄页数据。
用到了下面四个模块,前两个需要安装,后两个是用python搭建的。
import requests
from bs4 import BeautifulSoup
import csv
import time
然后,写一个函数来获取页面上你想要的数据,记得在最后返回,因为下面的函数需要将数据写入csv。
def get_content(url,data=None):
header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.104 Safari/537.36',
}
r = requests.get(url, headers=header)
soup = BeautifulSoup(r.content, 'html.parser')
data = soup.body.find('div',{'id':'news_con'})
ul = data.find('ul')
lis = ul.find_all('li')
pthons=[]
for item in lis:
rows=[]
name= item.find('h4').string
rows.append(name)
tel = item.find_all("div")[2].string
rows.append(tel)
pthons.append(rows)
time.sleep(1)
return pthons
下一步:将数据写入表中。我这里用的是csv,方便阅读。
def write_data(data,name):
file_name=name
with open(file_name, "w", newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["商铺名称", "联系电话"])
writer.writerows(data)
print('抓取完成')
最后一步是执行这些函数:
if __name__ == '__main__':
url = 'http://ty.114chn.com/CustomerInfo/Customers?cid=008004008&page=2'
mydata = get_content(url)
write_data(mydata,'phone.csv')
这里我觉得应该把url写成动态的,因为里面有页面。让页面写成循环自动+1,当然可以看到网页有多少个页面。写一个循环执行。它更完美。