我正在尝试从“thegolfcourse.net”网站提取高尔夫球场信息。我的目标是从网站上收集美国 18000 多个高尔夫球场的名称、地址和电话号码。我运行了我的脚本,但它没有生成网站上的所有数据。有 18000 多个高尔夫球场,但我只从该网站下载了大约 200 多个网站。我不知道我的循环是否错误,或者我没有根据我的代码访问所有数据,而且我的数据中出现空格,我想知道如何正确提取数据。
这是我的脚本:
import csv
import requests
from bs4 import BeautifulSoup
courses_list = []
for i in range(56):
url="http://www.thegolfcourses.net/page/{}?ls&location&orderby=title".format(i)
r = requests.get(url)
soup = BeautifulSoup(r.content)
g_data2=soup.find_all("article")
for item in g_data2:
try:
name = item.contents[5].find_all("a")[0].text
print name
except:
name=''
try:
phone= item.contents[13].find_all("p",{"class":"listing-phone"})[0].text
except:
phone=''
try:
address= item.contents[13].find_all("p",{"class":"listing-address"})[0].text
except:
address=''
course=[name,phone,address]
courses_list.append(course)
with open ('PGN.csv','a') as file:
writer=csv.writer(file)
for row in courses_list:
writer.writerow([s.encode("utf-8") for s in row])
首先,您的代码没有获取所有内容,因为您将范围设置为 56。这对于测试来说很好,但如果您想获取所有内容,则需要设置
for i in range(1907):
这会转到 1907,因为由于将
.format(i+1)
添加到 URL 部分,它将停止在 1907。
此外,您的
for
循环中有几个错误。当您发布到 StackOverflow 时,这些可能是问题,但我还是清理了它们。
当我第一次运行你的代码时,我看到“间距”是什么。当您解析 HTML 时,您会解析它以查找
article
标签,但该标签也会处理在示例链接中显示 "Listings found for "" near ""
的第一个搜索结果。您可以使用我在这里所做的事情来缩小网页抓取的范围:
g_data2 = soup.find_all("article",{"itemtype":"http://schema.org/Organization"})
这将使您通过仅抓取包含
article
和 itemtype = http://schema.org/Organization"
的标签中找到的数据来更轻松地进行抓取。这足够独特,幸运的是所有条目都符合该格式。
我还将您的
csvwriter
从 a
更改为 wb
,每次运行脚本时都会启动一个新的 CSV 并且不会附加到它。
这是最终脚本:
import csv
import requests
from bs4 import BeautifulSoup
courses_list = []
for i in range(1907):
url="http://www.thegolfcourses.net/page/{}?ls&location&orderby=title".format(i+1)
r = requests.get(url)
soup = BeautifulSoup(r.text)
#print soup
g_data2 = soup.find_all("article",{"itemtype":"http://schema.org/Organization"})
for item in g_data2:
try:
name = item.find_all("h2",{'class':'entry-title'})[0].text
print name
except:
name=''
print "No Name found!"
try:
phone= item.find_all("p",{"class":"listing-phone"})[0].text
except:
phone=''
print "No Phone found!"
try:
address= item.find_all("p",{"class":"listing-address"})[0].text
except:
address=''
print "No Address found!"
course=[name,phone,address]
courses_list.append(course)
with open ('PGN.csv','wb') as file:
writer=csv.writer(file)
for row in courses_list:
writer.writerow([s.encode("utf-8") for s in row])