python程序未运行

2024-04-25 02:31:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过PyCharm CE 2018.3.4用Python编写了一些脚本,但是当我运行这个脚本时,它永远不会显示结果,也永远不会结束。是因为魅力还是因为剧本

import requests
from bs4 import BeautifulSoup


def trade_spider(max_pages):
    page = 1
    while page <=1:
        url = "https://www.ebay.com/sch/i.html?_from=R40&_nkw=car&_sacat=0&_pgn="+str(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text,"html.parser")
        for link in soup.findAll('a',{'class' :'item-name' }):
            href = link.get('href')
            title = link.string
            print(href)
            print(title)

trade_spider(2)

Tags: textfromimport脚本urlsourcehtmlpage
3条回答

这是一个代码问题。您正在设置page=1,并且从不增加值。所以while循环永远不会结束

while循环的主要语句是:while page <=1:,但它永远不会增加,'page'值总是1。如果您想让它爬网2页,就像您正在尝试的那样,我相信应该是这样的:

def trade_spider(max_pages):
    page = 1
    #Loop until page number equals max_pages value
    while page <= max_pages:
         url = "https://www.ebay.com/sch/i.html?_from=R40&_nkw=car&_sacat=0&_pgn="+str(page)
         source_code = requests.get(url)
         plain_text = source_code.text
         soup = BeautifulSoup(plain_text,"html.parser")
         for link in soup.findAll('a',{'class' :'item-name' }):
             href = link.get('href')
             title = link.string
             print(href)
             print(title)
         #Increment page so it crawls next one on each iteration
         page+=1

首先,你有一个无限循环:

page = 1
while page <= 1:
    # Code in which page never changes

page总是总是1,因此您无法离开循环

至于不打印任何内容,您不断地从该站点获取第一页。一个简单的print结果显示,该页上没有class条目。因此,没有什么可打印的

请尝试以下操作:

for page in range(1, max_pages+1):
    url = "https://www.ebay.com/sch/i.html?_from=R40&_nkw=car&_sacat=0&_pgn="+str(page)

相关问题 更多 >