【问题标题】:How would you simplify this program? Python [closed]你会如何简化这个程序? Python [关闭]
【发布时间】:2016-10-19 11:11:51
【问题描述】:

我写了这个程序,目的是访问链接列表中的第18个链接,然后在新页面上再次访问第18个链接。

这个程序按预期工作,但它有点重复和不雅。

我想知道您是否对如何在不使用任何函数的情况下使其更简单有任何想法。如果我想重复这个过程 10 或 100 次,这会变得很长。

感谢您的任何建议!

# Note - this code must run in Python 2.x and you must download
# http://www.pythonlearn.com/code/BeautifulSoup.py
# Into the same folder as this program

import urllib
from BeautifulSoup import *

url = raw_input('Enter - ')
if len(url) < 1 :
    url='http://python-data.dr-chuck.net/known_by_Oluwanifemi.html'
html = urllib.urlopen(url).read()
soup = BeautifulSoup(html)

# Retrieve all of the anchor tags
tags = soup('a')
urllist = list()
count = 0
loopcount = 0
for tag in tags:
    count = count + 1
    tg = tag.get('href', None)
    if count == 18:
        print count, tg
        urllist.append(tg)


url2 = (urllist[0])
html2 = urllib.urlopen(url2).read()
soup2 = BeautifulSoup(html2)

tags2 = soup2('a')
count2 = 0
for tag2 in tags2:
    count2 = count2 + 1
    tg2 = tag2.get('href', None)
    if count2 == 18:
        print count2, tg2
        urllist.append(tg2)

【问题讨论】:

  • 不使用 XPath?
  • 这个属于codereview.stackexchange.com
  • 那说“我还没有学过函数”可能会促使那里的审阅者建议你了解它们。
  • 你需要函数...看看重复的代码
  • 保持原样,直到您了解函数。每当你发现自己在重复代码块时,你就需要函数

标签: python python-2.7


【解决方案1】:

这是你可以做的。

import urllib
from BeautifulSoup import *

url_1 = input('') or 'http://python-data.dr-chuck.net/known_by_Oluwanifemi.html'

html_1 = urllib.urlopen(url_1).read()
soup_1 = BeautifulSoup(html_1)

tags = soup('a')
url_retr1 = tags[17].get('href', None)

html_2 = urllib.urlopen(url_retr1).read()
soup_2 = BeautifulSoup(html_2)

tags_2 = soup_2('a')
url_retr1 = tags_2[17].get('href', None)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-09
    相关资源
    最近更新 更多