Python-使用BeautifulSoup遍历页面

时间:2018-12-06 10:41:05

标签: python beautifulsoup

我使用BeautifulSoup4从一些网页上抓取数据。例如,在以下情况下,URL为https://wadsfred.aliexpress.com/store/425826/search/1.html,共有96页。我的问题是该脚本在几页后抛出了一个错误。通常,当代码到达第15-20页时。错误消息:

回溯(最近通话最近):   在第34行的文件“ main.py”中     如果next_page.text!='下一步': AttributeError:'NoneType'对象没有属性'text'

谢谢您的帮助!

import requests
import os
import csv
from itertools import count
from bs4 import BeautifulSoup

os.chdir('C:\MyFolder')
page_nr = 1
price = []
min_order = []
prod_name = []

for page_number in count(start = 1):
    url = 
'https://wadsfred.aliexpress.com/store/425826/search/{}'.format(page_nr) + 
'.html'
    print(url)
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')
    for div_b in soup.find_all('div', {'class':'cost'}):
        price.append(div_b.text)

    for min_or in soup.find_all('span', {'class':'min-order'}):
        min_order.append(min_or.text)

    for pr_name in soup.find_all('div', {'class':'detail'}):
        for pr_h in pr_name.find_all('h3'):
            for pr_title in pr_h.find_all('a'):
                prod_name_s = (pr_title.get('title').strip())
                prod_name.append(prod_name_s[:120])

    print(len(prod_name))
    page_nr = page_nr + 1
    next_page = soup.find('a', {'class':'ui-pagination-next'})
    if next_page.text != 'Next':
      break

2 个答案:

答案 0 :(得分:1)

它已重定向到登录页面,将用户代理添加到您的请求中

heads = {"User-Agent" : 'Mozilla/5.0......'}
for page_number in count(start = 1):
    .....
    response = requests.get(url, headers=heads)

更好地使用requests.session()创建持久会话(cookie)

答案 1 :(得分:0)

在某些页面中可能没有带有类'ui-pagination-next'的'a'标签。 当您已经知道总共有96页时,可以跳过该检查。并将抓取块放入try catch中以跳过某些页面中的错误。