【问题标题】:python , run def() multiple timespython ,多次运行 def()
【发布时间】:2018-06-17 12:54:05
【问题描述】:

我编写了这段代码来获取 Ebay 价格 它要求提供完整的 ebay 链接,然后写下价格

import bs4 , requests
print('please enter full Ebay link  ..')
link = str(input())
def ebayprice(url):
    res = requests.get(link)
    res.raise_for_status()

    txt = bs4.BeautifulSoup(res.text , 'html.parser')
    csselement = txt.select('#mm-saleDscPrc')
    return csselement[0].text.strip()
price = ebayprice(link)

print('price is : '+ price)

我想改进它,我尽力了,但我做不到 我希望它获取多个链接并一个一个地运行它们,它应该每次都写结果 链接来自 input() 还是来自 links = 'www1,www2,www3' 无关紧要

【问题讨论】:

  • 使用循环语句
  • 您应该将res = requests.get(link) 替换为res = requests.get(url)。它目前使用全局链接而不是作为参数提供的 url

标签: python input


【解决方案1】:

您可以用逗号分隔并使用 for loop 遍历 list

def ebayprice(url):
    ...

for single_link in link.split(','):
    price = ebayprice(single_link)
    print('price for {} is {}'.format(single_link, price))

【讨论】:

    【解决方案2】:

    如果你愿意,你可以询问有多少链接,有人想抓取,然后你可以使用 for 循环语句遍历每个 url

    import bs4 , requests
    # ask how many links he will pass
    print('How many links do you want wo scrape ?')
    link_numb = int(input())
    
    # get the links 
    print('please enter full Ebay link  ..')
    links = [input() for _ in range(link_numb)]
    
    def ebayprice(link):
        res = requests.get(link)
        res.raise_for_status()
    
        txt = bs4.BeautifulSoup(res.text , 'html.parser')
        csselement = txt.select('#mm-saleDscPrc')
        return csselement[0].text.strip()
    
    for link in links:
        price = ebayprice(link)
        print(price)
    

    例子:

    How many links do you want wo scrape ?
    2
    please enter full Ebay link  ..
    http://example.com
    http://example-just-test.com
    # simple print the url
    http://example.com
    http://example-just-test.com
    

    【讨论】:

      猜你喜欢
      • 2022-07-27
      • 1970-01-01
      • 2018-09-25
      • 2021-08-18
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      相关资源
      最近更新 更多