我从特定网站中提取了项目,现在想将它们写入.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的样子:
我尝试打印你的汤调用的结果,例如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浏览器: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'})
您现在可以获得所需的输出。
有些网站拒绝没有用户代理的请求,而且这个网站看起来是这样做的。添加用户代理会使您的请求看起来更正常,以便网站允许它通过。这个或任何东西都没有任何标准,它因网站而异。