我刚学习Python网络爬虫,尝试获取加拿大不同Winmar位置的地址,并将结果放入CSV文件中。到目前为止,我发现唯一区分不同位置网站的方法是地址末尾的代码(数字)。问题是,当程序运行时,结果不会改变,而是在打印和写入CSV文件时产生第一个位置(305)的结果。感谢您的时间和考虑!
以下是我的代码:
import csv
import requests
from bs4 import BeautifulSoup
x = 0
numbers = ['305', '405', '306', '307', '308', '309', '4273']
f = csv.writer(open('Winmar_locations.csv', 'w'))
f.writerow(['City:', 'Address:'])
for links in numbers:
for x in range(0, 6):
url = 'https://www.winmar.ca/find-a-location/' + str(numbers[x])
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
location_name = soup.find("div", attrs={"class": "title_block"})
location_name_items = location_name.find_all('h2')
location_list = soup.find(class_='quick_info')
location_list_items = location_list.find_all('p')
for name in location_name_items:
names = name.text
names = names.replace('Location | ', '')
for location in location_list_items:
locations = location.text.strip()
locations = locations.replace('24 Hour Emergency | (902) 679-1116','')
print(names, locations)
x = x+1
f.writerow([names, locations])