【发布时间】:2020-09-06 06:28:52
【问题描述】:
这里是屏幕抓取的新手,这是我第一次在 stackoverflow 上发帖。提前为这篇文章中的任何格式错误道歉。尝试从具有 URL 的多个页面中提取数据: https://www.landwatch.com/Michigan_land_for_sale/West_Central_Region/Page-' + str(page)
例如,第 1 页是:
https://www.landwatch.com/Michigan_land_for_sale/West_Central_Region/Page-1
第 2 页: https://www.landwatch.com/Michigan_land_for_sale/West_Central_Region/Page-2
等等……
我的脚本运行没有错误。但是,我的 Pandas 导出的 csv 仅包含 1 行,其中包含第一个提取值。在此发布时,第一个值为:
14.01 Acres  Vestaburg, Montcalm County, MI$275,000
我的意图是创建一个包含数百行的电子表格,用于从 URL 中提取属性描述。
这是我的代码:
import requests
from requests import get
from bs4 import BeautifulSoup
headers = ({'User-Agent':
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
}
)
n_pages = 0
desc = []
for page in range(1,900):
n_pages += 1
sapo_url = 'https://www.landwatch.com/Michigan_land_for_sale/West_Central_Region/Page-' + str(page)
r=get(sapo_url, headers=headers)
page_html = BeautifulSoup(r.text, 'html.parser')
house_containers = page_html.find_all('div', class_="propName")
if house_containers != []:
for container in house_containers:
desc = container.getText(strip=True)
else:
break
print('you scraped {} pages containing {} Properties'.format(n_pages, len(desc)))
import pandas as pd
df = pd.DataFrame({'description': [desc]})
df.to_csv('test4.csv', encoding = 'utf-8')
我怀疑问题出在 desc = container.getText(strip=True) 的行上,并尝试更改行,但在运行时不断出错。
感谢任何帮助。
【问题讨论】:
标签: python pandas beautifulsoup