import requests from bs4 import BeautifulSoup import openpyxl from time import sleep # 设置请求头,模拟浏览器访问 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'} # 从天眼查获取公司邮箱和电话 def get_info(company): email = '' phone = '' url = 'https://www.tianyancha.com/search?key=' + company r = requests.get(url, headers=headers) soup = BeautifulSoup(r.text, 'html.parser') # try: # 获取公司详情页链接 company_url = soup.find_all('a', class_='index_alink__zcia5 link-click')[0].get('href') r = requests.get(company_url, headers=headers) soup = BeautifulSoup(r.text, 'html.parser') # 获取公司邮箱和电话 email = soup.find_all('span', class_='index_detail-email__B_1Tq')[0].text sleep(0.5) phone = soup.find('span',class_='index_detail-tel__fgpsE').text # except: # pass # return email,phone # 从Excel文件中读取公司名称 def read_from_excel(file_path): wb = openpyxl.load_workbook(file_path) ws = wb.active company_list = [] for row in ws.iter_rows(min_row=2, values_only=True): company_list.append(row[0]) return company_list # 将公司邮箱和电话写入Excel文件 def write_to_excel(company_list): wb = openpyxl.Workbook() ws = wb.active ws.title = 'Company Info' # 写入表头 ws.cell(row=1, column=1, value='Company Name') ws.cell(row=1, column=2, value='Email') ws.cell(row=1, column=3, value='Phone') # 写入数据 for i, company in enumerate(company_list): email,phone = get_info(company) ws.cell(row=i+2, column=1, value=company) ws.cell(row=i+2, column=2, value=email) ws.cell(row=i+2, column=3, value=phone) # 保存Excel文件 wb.save('company_info.xlsx') if __name__ == '__main__': file_path = 'company_names.xlsx' company_list = read_from_excel(file_path) write_to_excel(company_list)优化这段代码
时间: 2024-04-21 17:28:13 浏览: 161
这段代码可以进行以下优化:
1. 在函数 get_info 中,使用 try...except 捕获异常会使代码难以维护。可以使用 if...else 判断 soup.find_all() 和 soup.find() 是否返回了有效结果,如果无效则将 email 和 phone 赋值为空字符串。
2. 在函数 write_to_excel 中,每次调用 get_info() 都会发起一个 http 请求,这会导致程序运行速度变慢。可以先将所有公司的详情页链接获取到,再一次性请求,减少 http 请求的次数。
下面是优化后的代码:
```
import requests
from bs4 import BeautifulSoup
import openpyxl
from time import sleep
# 设置请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
}
# 从天眼查获取公司邮箱和电话
def get_info(company, company_urls):
email = ''
phone = ''
url = 'https://www.tianyancha.com/search?key=' + company
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
# 获取公司详情页链接
company_url = soup.find_all('a', class_='index_alink__zcia5 link-click')
if company_url:
company_urls.append(company_url[0].get('href'))
# 获取公司邮箱和电话
if company_urls:
r = requests.get(company_urls[-1], headers=headers)
soup = BeautifulSoup(r.text, 'html.parser')
email = soup.find('span', class_='index_detail-email__B_1Tq')
phone = soup.find('span', class_='index_detail-tel__fgpsE')
if email:
email = email.text
if phone:
phone = phone.text
sleep(0.5)
return email, phone
# 从Excel文件中读取公司名称
def read_from_excel(file_path):
wb = openpyxl.load_workbook(file_path)
ws = wb.active
company_list = []
for row in ws.iter_rows(min_row=2, values_only=True):
company_list.append(row[0])
return company_list
# 将公司邮箱和电话写入Excel文件
def write_to_excel(company_list):
company_urls = []
for company in company_list:
email, phone = get_info(company, company_urls)
company_urls.pop()
row_num = len(company_urls) + 2
ws.cell(row=row_num, column=1, value=company)
ws.cell(row=row_num, column=2, value=email)
ws.cell(row=row_num, column=3, value=phone)
# 保存Excel文件
wb.save('company_info.xlsx')
if __name__ == '__main__':
file_path = 'company_names.xlsx'
company_list = read_from_excel(file_path)
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Company Info'
# 写入表头
ws.cell(row=1, column=1, value='Company Name')
ws.cell(row=1, column=2, value='Email')
ws.cell(row=1, column=3, value='Phone')
write_to_excel(company_list)
```
阅读全文