python - 网页抓取多个相似页面

标签 python web-scraping beautifulsoup

我是 python 网络抓取的新手,我试图获取加拿大不同 winmar 位置的地址,并将结果放入 csv 文件中。到目前为止,我发现区分不同位置站点的唯一方法是通过地址末尾的代码(数字)。问题是结果不会随着程序运行而改变,而是在打印时产生第一个位置 (305) 的结果,并将结果写入 csv 文件。感谢您的时间和考虑!

这是我的代码:

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])

最佳答案

你的代码有一些错误,还有一个关于你正在抓取的网站的错误

  • 首先像这样访问 url https://www.winmar.ca/find-a-location/308 不会正确更改位置,它需要像这样 https://www.winmar.ca/find-a-location/#308 在数字前加上 hashbang。

  • 该网站有相同类的重复 html,这意味着您几乎一直加载所有位置,而他们只是从他们的 js 代码中选择要显示的位置 - 当然是不好的做法 -,这使得您的匹配器总是得到相同的位置,这就解释了为什么您总是重复相同的位置。

  • 最后,你有很多不必要的循环,你只需要遍历数字数组就可以了。

这是你的代码的修改版本

import csv
import requests
from bs4 import BeautifulSoup

x = 0
numbers = ['305', '405', '306', '307', '308', '309', '4273']


names = []
locations = []
for x in range(0, 6):
    url = 'https://www.winmar.ca/find-a-location/#' + str(numbers[x])
    print(f"pinging url {url}")

    r = requests.get(url)
    soup = BeautifulSoup(r.content, "html.parser")
    scope = soup.find(attrs={"data-id": str(numbers[x])})

    location_name = scope.find("div", attrs={"class": "title_block"})
    location_name_items = location_name.find_all('h2')


    location_list = scope.find(class_='quick_info')
    location_list_items = location_list.find_all('p')

    name = location_name.find_all("h2")[0].text
    print(name)

    names.append(name)

    for location in location_list_items:
        loc = location.text.strip()
        if '24 Hour Emergency' in loc: 
            continue
        print(loc)
        locations.append(loc)

    x = x+1

注意我所做的范围界定

    scope = soup.find(attrs={"data-id": str(numbers[x])})

这使您的代码不受它们在 html 中加载了多少位置的影响,您只需将范围定位到您想要的位置。

这导致:

pinging url https://www.winmar.ca/find-a-location/#305
Location | Annapolis
70 Donald E Hiltz Connector Road
Kentville, NS
B4N 3V7
pinging url https://www.winmar.ca/find-a-location/#405
Location | Bridgewater
15585 Highway # 3
Hebbville, NS
B4V 6X7
pinging url https://www.winmar.ca/find-a-location/#306
Location | Halifax
9 Isnor Dr
Dartmouth, NS
B3B 1M1
pinging url https://www.winmar.ca/find-a-location/#307
Location | New Glasgow
5074 Hwy. #4, RR #1
Westville, NS
B0K 2A0
pinging url https://www.winmar.ca/find-a-location/#308
Location | Port Hawkesbury
8 Industrial Park Rd
Lennox Passage, NS
B0E 1V0
pinging url https://www.winmar.ca/find-a-location/#309
Location | Sydney
358 Keltic Drive
Sydney River, NS
B1R 1V7

关于python - 网页抓取多个相似页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61165627/

相关文章:

python - 如何从经过训练的 Tensorflow 分类器获得类别预测?

python - Pandas Dataframe内存read_csv

jquery - 抓取使用ajax的网页

Python不会写入文件

python - 如何使用 Python 从容器内的文本中抓取 Td

python - SDE 的 ListFeatureClasses() 故障

python - 在 Ubuntu 16.04 上使用 Apache mod_wsgi 部署 Bottle.py 应用程序

python - 如何从通过 JavaScript 加载的页面的 XHR 请求中自动检索请求 URL(对于 python)

python - 如何用 beautiful soup 来抓取没有 class 或 id 的元素

python - BS4 网络抓取到 CSV 文件,我认为我抓取了太多行 ('tr' )s