Python脚本的命令行输入

时间:2014-04-16 08:27:09

标签: python html beautifulsoup yelp

我想在这里做什么:

我正在尝试抓取yelp并从特定页面获取评论。但是,我只想修改此脚本以提供" 餐厅名称"作为输入。

例如:

用户输入: 的丹尼斯-SAN-圣何塞-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)

但它不起作用。我从命令行(python script.py dennys-san-jose-5)输入 dennys-san-jose-5

请在此处告诉我这个问题以及我如何解决。

此致

1 个答案:

答案 0 :(得分: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: user input and commandline arguments