使用 Python 抓取多个页面仅重复第一页

Scraping multiple pages with Python repeats only the first page

我正在尝试抓取此页面 https://www.anesishome.gr/%CE%B2%CF%81%CE%B5%CF%86%CE%B9%CE%BA%CE%AC-159#!/ 我需要前 5 页的每种产品的名称和价格。问题是我的代码给出了第一页的结果 5 次。就好像我不更改下一页的 url 一样。我究竟做错了什么?谢谢!

from urllib.request import urlopen
from bs4 import BeautifulSoup
for i in range(5):
    page="https://www.anesishome.gr/%CE%B2%CF%81%CE%B5%CF%86%CE%B9%CE%BA%CE%AC-159#!/page-{}".format(i)
    html = urlopen(page)
    soup=BeautifulSoup(html, "html.parser")
    pin=[None]*240
    puk=[None]*240
    k=soup.find("ul", class_="product-grid row")
    titles=k.find_all("a", class_="product_image")
    i=0
    for title in titles:
        pin[i]=title.get("title")
        i=i+1  
    t=soup.find("ul", class_="product-grid row")
    prices=t.find_all("span", class_="price")
    i=0
    for price in prices:
        puk[i]=price.get_text()
        i=i+1
    x=0
    with open('vrefika.txt', 'w') as f:
        for x in range(0,i):
            print(pin[x])
            print("price=",puk[x])
            string=pin[x]
            f.write(string+"\n")
            string=puk[x]
            f.write(string+"\n")

此页面使用 JavaScript/AJAX 加载下一页 - 此 AJAX 使用 url

https://www.anesishome.gr/modules/blocklayered/blocklayered-ajax.php?id_category_layered=159&layered_price_slider=2_350&orderby=price&orderway=asc&n=48&p=2&_=1486296430052

p=2 是页码。

结果是 JSON 字符串

{"filtersBlock":"<script type=\"text\/javascript\">\ncurrent_friendly_url = '#!\/page-2';\nparam_product_url

但也许您可以使用字符串切片通过使用 JSON module/parser.

来获得 HTML

我为您制作了一个演示,希望对您有所帮助:

import requests
from bs4 import BeautifulSoup
for i in range(1, 6):  # page start at 1, end with 5 
    page="https://www.anesishome.gr/%CE%B2%CF%81%CE%B5%CF%86%CE%B9%CE%BA%CE%AC-159?p={}".format(i)
    html = requests.get(page)
    soup = BeautifulSoup(html.text, 'lxml')
    product_list = soup.find('div', id="product_list")  # get product_list

    for item in product_list('li', class_='ajax_block_product'): # itertate over each product
        title = item.find('h5').text
        price = item.find(class_="price").text
        print(title, price)

输出:

ΠΕΤΣΕΤΑ ΒΡΕΦΙΚΗ NEF - NEF HAPPY DAY MINT 40X60 2,66 €
ΠΑΙΔΙΚΗ ΠΕΤΣΕΤΑ ΧΕΡΙΩΝ NEF - NEF SNOOPY FRIENDS 3,50 €
Πετσετάκια ώμου σε σετ 3 τεμαχίων Pierre Cardin 4,80 €
Σαλιάρα Pierre Cardin 74 5,60 €
Σαλιάρα Pierre Cardin 135 5,60 €
ΒΡΕΦΙΚΟ ΜΑΞΙΛΑΡΙ ΜΑΛΑΚΟ NEF-NEF BALLFIBER 6,75 €
ΣΑΛΙΑΡΑ NEF-NEF TINY FRIENDS 7,20 €
ΣΑΛΙΑΡΑ NEF-NEF PLAY NOW 7,20 €
Pierre Cardin baby design 035 Πάνες Φανελένιες 7,20 €
Pierre Cardin baby design 036 Πάνες Φανελένιες 7,20 €
Baby Oliver design 212 Πάνες χασέ 7,20 €