抓取 url 列表

Scraping a list of urls

我正在使用 Python 3.5 并尝试抓取一个 url 列表(来自同一网站),代码如下:

import urllib.request
from bs4 import BeautifulSoup



url_list = ['URL1',
            'URL2','URL3]

def soup():
    for url in url_list:
        sauce = urllib.request.urlopen(url)
        for things in sauce:
            soup_maker = BeautifulSoup(things, 'html.parser')
            return soup_maker

# Scraping
def getPropNames():
    for propName in soup.findAll('div', class_="property-cta"):
        for h1 in propName.findAll('h1'):
            print(h1.text)

def getPrice():
    for price in soup.findAll('p', class_="room-price"):
        print(price.text)

def getRoom():
    for theRoom in soup.findAll('div', class_="featured-item-inner"):
        for h5 in theRoom.findAll('h5'):
            print(h5.text)


for soups in soup():
    getPropNames()
    getPrice()
    getRoom()

到目前为止,如果我打印 soup、get propNames、getPrice 或 getRoom,它们似乎都有效。但我似乎无法让它通过每个 url 并打印 getPropNames、getPrice 和 getRoom。

才学习 Python 几个月,所以非常感谢您对此提供的帮助!

想想这段代码的作用:

def soup():
    for url in url_list:
        sauce = urllib.request.urlopen(url)
        for things in sauce:
            soup_maker = BeautifulSoup(things, 'html.parser')
            return soup_maker

举个例子:

def soup2():
    for url in url_list:
        print(url)
        for thing in ['a', 'b', 'c']:
            print(url, thing)
            maker = 2 * thing
            return maker

url_list = ['one', 'two', 'three'] 的输出是:

one
('one', 'a')

你现在看到了吗?到底是怎么回事?

基本上你的 soup 函数 return 首先 return - 不要 return 任何迭代器,任何列表;只有第一个 BeautifulSoup - 你很幸运(或不幸运)这是可迭代的:)

所以修改代码:

def soup3():
    soups = []
    for url in url_list:
        print(url)
        for thing in ['a', 'b', 'c']:
            print(url, thing)
            maker = 2 * thing
            soups.append(maker)
    return soups

然后输出为:

one
('one', 'a')
('one', 'b')
('one', 'c')
two
('two', 'a')
('two', 'b')
('two', 'c')
three
('three', 'a')
('three', 'b')
('three', 'c')

但我相信这也行不通 :) 只是想知道 sauce return 编辑了什么:sauce = urllib.request.urlopen(url) 实际上你的代码迭代的是什么:for things in sauce - things 是什么意思。

编码愉快。

每个 get* 函数都使用一个全局变量 soup,但在任何地方都没有正确设置。即便如此,也不是什么好办法。使 soup 成为函数参数,例如:

def getRoom(soup):
    for theRoom in soup.findAll('div', class_="featured-item-inner"):
        for h5 in theRoom.findAll('h5'):
            print(h5.text)

for soup in soups():
    getPropNames(soup)
    getPrice(soup)
    getRoom(soup)

其次,你应该从 soup() 而不是 returnyield 来把它变成一个发电机。否则,您将需要 return 一个包含 BeautifulSoup 个对象的列表。

def soups():
    for url in url_list:
        sauce = urllib.request.urlopen(url)
        for things in sauce:
            soup_maker = BeautifulSoup(things, 'html.parser')
            yield soup_maker

我还建议使用 XPath 或 CSS 选择器来提取 HTML 元素:.