【问题标题】:Add a string into a url python将字符串添加到 url python
【发布时间】:2017-06-26 13:37:32
【问题描述】:

我正在尝试在 url 中间添加一个字符串。不知何故,我的输出看起来像这样:

http://www.Holiday.com/('Woman',)/Beach
http://www.Holiday.com/('Men',)/Beach

不知怎的,它应该是这样的:

http://www.Holiday.com/Woman/Beach
http://www.Holiday.com/Men/Beach

我使用的代码如下所示:

list = {'Woman','Men'}
url_test = 'http://www.Holiday.com/{}/Beach'
for i in zip(list):
    url = url_test.format(str(i))
    print(url)

【问题讨论】:

  • 你看到打印了什么?
  • 请不要使用list作为变量名。

标签: python string list url


【解决方案1】:

差不多了。只是不需要zip

items = {'Woman','Men'} # notice that this is a `set` and not a list
url_test = 'http://www.Holiday.com/{}/Beach'
for i in items:
    url = url_test.format(i)
    print(url)

zip 函数的目的是通过索引加入多个集合。当zip 加入来自每个集合的值时,它将它们放在tuple 中,它的__str__ 表示正是你得到的。 这里你只想迭代集合中的项目

【讨论】:

  • 值得一提的是,list 不是一个好的 var 名称,str(您已删除)是不必要的
  • @brianpck - true :) 特别是它实际上是set
  • @GiladGreen,非常感谢我正在寻找的东西。不知何故,我误解了 zip 的使用。
【解决方案2】:

你也可以试试这个,请不要使用list作为变量名。

lst = {'Woman','Men'}
url_test = 'http://www.Holiday.com/%s/Beach'
for i in lst:
     url = url_test %i
     print url

【讨论】:

    【解决方案3】:
    from urllib.request import urlopen
    from bs4 import BeautifulSoup as BS
    url = "https://www.imdb.com/chart/top?ref_=nv_mv_250"
    html = urlopen(url)
    
    url_list = BS(html, 'lxml')
    type(url_list)
    
    all_links = url_list.find_all('a', href=re.compile("/title/tt"))
    for link in all_links:
      print(link.get("href"))
    all_urls = link.get("href")
    
    url_test = 'http://www.imdb.com/{}/'
    for i in all_urls:
        urls = url_test.format(i)
        print(urls)
    
        this is the code to scrape the urls of all the 250 movies from the main url.
        but the code gives the result as ------
    
        http://www.imdb.com///
        http://www.imdb.com/t/
        http://www.imdb.com/i/
        http://www.imdb.com/t/
        http://www.imdb.com/l/
        http://www.imdb.com/e/
        http://www.imdb.com///
        and so on ...
    
        how can i split 'all_urls' using a comma, or how can I make a list of urls in 
        'all_urls'....
    

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      • 2018-03-26
      相关资源
      最近更新 更多