Python脚本的命令行输入

0 投票
1 回答
1555 浏览
提问于 2025-04-18 02:56

我想要做的事情:

我想要抓取yelp网站上的评论,特别是从某个页面获取评论。不过,我只是想修改这个脚本,让它可以接受“餐厅名称”作为输入。

举个例子:

用户输入: dennys-san-jose-5

URL: http://www.yelp.com/biz/**dennys-san-jose-5**

这是我现在正在使用的实际脚本:

from bs4 import BeautifulSoup
from urllib import urlopen
queries = 0
while queries <201:
    stringQ = str(queries)
    page = urlopen('http://www.yelp.com/biz/madison-square-park-new-york?start=' + stringQ)

    soup = BeautifulSoup(page)
    reviews = soup.findAll('p', attrs={'itemprop':'description'})
    authors = soup.findAll('span', attrs={'itemprop':'author'})

    flag = True
    indexOf = 1
    for review in reviews:
        dirtyEntry = str(review)
        while dirtyEntry.index('<') != -1:
            indexOf = dirtyEntry.index('<')
            endOf = dirtyEntry.index('>')
            if flag:
                dirtyEntry = dirtyEntry[endOf+1:]
                flag = False
            else:
                if(endOf+1 == len(dirtyEntry)):
                    cleanEntry = dirtyEntry[0:indexOf]
                    break
                else:
                    dirtyEntry = dirtyEntry[0:indexOf]+dirtyEntry[endOf+1:]
        f=open("reviews.txt", "a")
        f.write(cleanEntry)
        f.write("\n")
        f.close

    for author in authors:
        dirty = str(author)
        closing = dirty.index('>')
        dirty = dirty[closing+1:]
        opening = dirty.index('<')
        cleanEntry = dirty[0:opening]
        f=open("bla.txt", "a")
        f.write(cleanEntry)
        f.write("\n")
        f.close 
    queries = queries + 40

我想把餐厅名称当作参数来读取,但不知道为什么不行。

我做了什么:

while queries <201:
    stringQ = str(queries)
    page = urlopen('http://www.yelp.com/biz/' + stringQ)

但是它还是不工作。我是通过命令行输入dennys-san-jose-5(python script.py dennys-san-jose-5)来运行的。

请告诉我这里的问题是什么,以及我该如何修复。

谢谢,

1 个回答

2

要从命令行读取参数,你可以使用argparse这个工具。

import argparse

#Define command line arguments
parser = argparse.ArgumentParser(description='Get Yelp reviews.')
parser.add_argument("-p", "--page", dest="page", required=True, help="the page to parse")

#parse command line arguments
args = parser.parse_args()

你的页面名称现在会存储在args.page里。在这个例子中,你可以这样运行脚本:

>python script.py  -p dennys-san-jose-5

或者

>python script.py --page dennys-san-jose-5


补充说明:

  • 如果你不需要太复杂的功能,只想要原始的命令行输入(比如在一个只有你会用的程序里,不需要验证输入等):

    import sys
    print sys.argv
    
  • 如果你想在程序运行时提示用户输入页面名称,可以参考这个链接:Python: 用户输入和命令行参数

撰写回答