【问题标题】:Need help converting something from urllib2 to urllib3需要帮助将某些内容从 urllib2 转换为 urllib3
【发布时间】:2019-08-06 17:47:56
【问题描述】:

我正在尝试将下面的函数从 urllib2 调整为 urllib3。我遇到的问题是 urllib3 没有 openurl 属性。我将如何重写这些函数?

提前谢谢你。

def get_season_URLs(year):

if not year in VALID_YEARS :
    print (str(year) + " is an invalid year")
    return
base_url_schedule_1 = BASE_URL + "/leagues/NBA_" + str(year) + "_games-"
url_extensions = YEAR_ONE_MONTHS + YEAR_TWO_MONTHS    
urls = []

for extension in url_extensions :
    schedule_url = get_schedule_URL(year, extension)
    doc = BeautifulSoup(urllib2.urlopen(schedule_url).read(), "html.parser")
    schedule_table = doc.find_all("tbody")[0]
    box_score_els = schedule_table.find_all(attrs={"data-stat": "box_score_text"})

    for el in box_score_els :
        urls.append(BASE_URL + el.find("a").get('href'))
return urls

def scrape_game(url, f) :

html = urllib2.urlopen(url).read()
doc = BeautifulSoup(html, "html.parser")
if not len(doc.find_all(attrs={"data-label":"All Games in Series"})) == 0 :
    return False
line = ""```

【问题讨论】:

    标签: python urllib urllib2 urllib3


    【解决方案1】:

    你使用的是 BeautifulSoup,所以我猜你使用的是 python2.7:

    try:
            from urlllib2 import urlopen
    except ImportError:
            from urllib import urlopen
    

    并在您的通话中将 urllib2.urlopen 更改为简单的 urlopen

    在 python3 中,您需要将第二个 from 更改为 from urllib.request import urlopen,但您必须将 BeautifulSoup 调用更改为适当的 python3-ism。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      • 2018-11-24
      • 2019-12-23
      • 2021-11-06
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多