Beautifulsoup保存链接到列表

Pot*_*Box -1 python beautifulsoup

我正在尝试从某个网站检索链接并将其保存到列表中以供进一步使用.到目前为止我得到的(这是我存储输出的.txt文件):

<ul>
<li><a class="active" href="/review/huerco-s-those-you-who-have-never-and-also-those-w/">Huerco S.<span><i>For Those Of You Who Have Never (And  Also Those Who Have)</i></span></a></li>
<li><a href="/review/dam-funk-dj-kicks/">Dâm-Funk<span><i>DJ-Kicks</i>  </span></a></li>
<li><a href="/review/skepta-konnichiwa/">Skepta<span><i>Konnichiwa</i></span></a></li>
<li><a href="/review/jessy-lanza-oh-no/">Jessy Lanza<span><i>Oh No</i></span></a></li>
<li><a href="/review/radiohead-moon-shaped-pool/">Radiohead<span><i>A Moon Shaped Pool</i></span></a></li>
<li><a href="/review/brodka-clashes/">Brodka<span><i>Clashes</i></span></a></li>
<li><a href="/review/james-blake-colour-anything/">James Blake<span><i> The Colour In Anything</i></span></a></li>
<li><a href="/review/kamaiyah-good-night-ghetto/">Kamaiyah<span><i>A Good Night In The Ghetto</i></span></a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

我想将这些特定链接提取到列表中.我的代码:

website = "http://www.porcys.com/review/"
openWebsite = soup(urllib.request.urlopen(website), 'html.parser')
reviews = openWebsite.find(name="section", attrs={'class': 'slider-content review'}).ul
for a in reviews(href = True):
    temp = str("http://www.porcys.com"+str(a['href']))
    print(temp)
Run Code Online (Sandbox Code Playgroud)

打印输出正是我想要的(这意味着 - 只是链接,没有任何HTML标签),但我将它移动到列表有困难.我试过了

results[a] = temp
a+=1
Run Code Online (Sandbox Code Playgroud)

但我得到"列表索引必须是整数或切片,而不是标签"

Bah*_*rom 5

您的错误正在发生,因为a是a Tag,并且您正在尝试访问结果的" Tag th"元素而不是" i th"元素,其中i是一些整数索引或切片.您可以做的是定义结果列表并附temp加到其中.

results = []
for a in reviews(href=True):
    temp = "http://www.porcys.com" + a['href']
    print(temp)
    results.append(temp)

print results
Run Code Online (Sandbox Code Playgroud)

您也可以在列表理解中执行此操作:

results = ["http://www.porcys.com"+a['href'] for a in reviews(href=True)]
print results
Run Code Online (Sandbox Code Playgroud)