【问题标题】:Choose, type and Parse with BeautifulSoup and Python syntax?使用 BeautifulSoup 和 Python 语法选择、输入和解析?
【发布时间】:2014-11-21 00:58:40
【问题描述】:

我是 BeautifulSoup 和 python 开发的新手,我想编写一个脚本来为我的个人网站自动化一些事情。

我做这个:

#!/usr/bin/env python

""" Test menu for Website
"""

import urllib2
from bs4 import BeautifulSoup

print (47 * '-')
print ("   C H O I C E   L I S T")
print (47 * '-')
print ("1. Page One")
print ("2. Page Two")
print ("3. Page Three")
print ("4. Page Four")
print (47 * '-')
print (47 * '-')

#############################
##  Robust error handling  ##
##  only accpet int        ##
#############################
## Wait for valid input in while...not ###

is_valid=0

while not is_valid :
        try :
                choice = int ( raw_input('Enter your choice [1-8] : ') )
                is_valid = 1 ## set it to 1 to validate input and to terminate the while..not loop
        except ValueError, e :
                print ("'%s' is not a valid choice." % e.args[0].split(": ")[1])


### Take action as per selected choice list option ###

if choice == 1:
        print ("www.mywebsite.com/page_one.html")
elif choice == 2:
        print ("www.mywebsite.com/page_two.html")
elif choice == 3:
        print ("www.mywebsite.com/page_three.html")
elif choice == 4:
        print ("www.mywebsite.com/page_four.html")
else:
        print ("Invalid choice. try again...")

print (47 * '-')
print (47 * '-')


username = raw_input("Please, type your username\n")


html_content = urllib2.urlopen("http://" + [choice] + "/" + username)

soup = BeautifulSoup(html_content, "lxml")

#####################
## STRINGS REPLACE ##
#####################

start_msg = "Hey, you have "
end_msg = "comments !"
end_str = "read !"


####################
## COMMENTS COUNT ##
####################

count_comments = soup.find("span", "sidebar-comments")
count_comments
count_comments_final = count_comments.find_next("meta")


################
## COUNT READ ##
################

count_read = soup.find("span", "sidebar-read")
count_read
count_read_final = count_read.find_next("meta")



##################
## PRINT RESULT ##
##################

print start_msg + count_comments_final['content'].split(':')[1] + end_msg
print start_msg + count_read_final['content'].split(':')[1] + end_str

有了这个脚本,我想要:

1 - 选择我的网页(选择列表 - 4)

2 - 输入我的用户名

3 - 解析我选择的网页并获取所有 cmets 和所有读取的计数。

我的问题在这里 html_content = urllib2.urlopen("http://" + [choice] + username) ,我无法检索一个好的 URL 所需的参数!

你能帮我找到正确的语法吗!

我的最终到达网址应该是:http://www.mywebsite.com/page_one.html/username

【问题讨论】:

    标签: python parsing beautifulsoup html-parsing lxml


    【解决方案1】:

    这是一个奇怪的 URL,但您唯一需要的是将 url 存储在变量中并重复使用。

    另外,我会使用字典来映射 int 选项和实际 url:

    mapping = {
        1: 'www.mywebsite.com/page_one.html',
        2: 'www.mywebsite.com/page_two.html', 
        3: 'www.mywebsite.com/page_three.html',
        4: 'www.mywebsite.com/page_four.html'
    }
    
    try:
        page = mapping[choice]
    except KeyError:
        print ("Invalid choice. try again...")
        # TODO: try again? :)
    
    username = raw_input("Please, type your username\n")
    
    url = "http://{page}/{username}".format(page=page, username=username)
    html_content = urllib2.urlopen(url)
    

    【讨论】:

    • 你能给我完整的代码吗,我不确定在好地方替换。我得到这个: Traceback(最近一次调用最后一次):文件“./testTwo.py”,第 46 行,在 page = mapping[choice] NameError: name 'choice' is not defined
    • 哦,对不起,我忘了说非常感谢您的帮助;-) 很抱歉成为初学者!
    • 我尝试了很多我认为对您的新代码合乎逻辑的不同事情,但我仍然有同样的错误:NameError: name 'choice' is not defined 我不明白!对不起
    • @TwinyTwice 应该有点像gist.github.com/alecxe/a303d06ecb61b5d07b03。希望对您有所帮助。
    • 非常非常感谢!我刚刚将映射放在 is_valid 部分之前!!!! ;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-04
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    相关资源
    最近更新 更多