我已经从特定网站提取了项目,现在想将它们写入.xls文件。
我希望完整的excel表格包含标题和信息行,但会得到仅包含标题的表格。
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
res = requests.get('https://www.raywhite.com/contact/?type=People&target=people&suburb=Sydney%2C+NSW+2000&radius=50%27%27&firstname=&lastname=&_so=contact')
soup = bs(res.content, 'lxml')
names=[]
positions=[]
phone=[]
emails=[]
links=[]
nlist = soup.find_all('li', class_='agent-name')
plist= soup.find_all('li',class_='agent-role')
phlist = soup.find_all('li', class_='agent-officenum')
elist = soup.find_all('a',class_='val withicon')
for n1 in nlist:
names.append(n1.text)
links.append(n1.get('href'))
for p1 in plist:
positions.append(p1.text)
for ph1 in phlist:
phone.append(ph1.text)
for e1 in elist:
emails.append(e1.get('href'))
df = pd.DataFrame(list(zip(names,positions,phone,emails,links)),columns=['Names','Position','Phone','Email','Link'])
df.to_excel(r'C:\Users\laptop\Desktop\RayWhite.xls', sheet_name='MyData2', index = False, header=True)
这是生成的DataFrame的样子:
答案 0 :(得分:0)
我尝试打印您的汤调用结果,例如nlist = soup.find_all('li', class_='agent-name')
,并返回空数组。汤功能未找到任何数据。
再看一遍,汤的请求又变空了:
soup = bs(res.content, 'lxml')
print(soup)
给予:
<html>
<head><title>429 Too Many Requests</title></head>
<body bgcolor="white">
<center><h1>429 Too Many Requests</h1></center>
<hr/><center>nginx</center>
</body>
</html>
该网站似乎将您检测为漫游器,并且不允许您抓取。您可以按照以下答案假装自己是网络浏览器:Web scraping with Python using BeautifulSoup 429 error
更新:
将用户代理添加到请求即可达到目的:
res = requests.get('https://www.raywhite.com/contact/?type=People&target=people&suburb=Sydney%2C+NSW+2000&radius=50%27%27&firstname=&lastname=&_so=contact', headers = {'User-agent': 'Super Bot 9000'})
您现在将获得所需的输出。
某些网站拒绝了没有用户代理的请求,并且该网站似乎拒绝了。添加用户代理使您的请求看起来更加正常,因此该站点允许它通过。其实并没有任何标准,它因站点而异。