在Python BeautifulSoup中提取带有href属性的链接

在Python BeautifulSoup中提取带有href属性的链接,python,beautifulsoup,Python,Beautifulsoup,我有一个简单的任务从html(url)中提取链接。我这样做: > #!/usr/bin/python > > import urllib import webbrowser from bs4 import BeautifulSoup > > URL = "http://54.75.225.110/quiz" URL_end = "/question" > > LINK = URL + URL_end file = > urllib.urlop

我有一个简单的任务从html(url)中提取链接。我这样做:

> #!/usr/bin/python
> 
> import urllib import webbrowser from bs4 import BeautifulSoup
> 
> URL = "http://54.75.225.110/quiz" URL_end = "/question"
> 
> LINK = URL + URL_end file =
> urllib.urlopen("http://54.75.225.110/quiz/question") soup =
> BeautifulSoup(file)
> 
> for item in soup.find_all(href=True):
>     print item
> 
> 
> print 'Hey there!'
这是html:

> <html><head><meta http-equiv="Content-Type" content="text/html;
> charset=ISO-8859-1"> <script
> src="./question_files/jquery.min.js"></script> <script
> type="text/javascript">
>        function n(s) {
>               var m = 0;
>               if (s.length == 0) return m;
>               for (i = 0; i < s.length; ++i) {
>                         o = s.charCodeAt(i);          m = ((m<<5)-m)+o;           m = m & m;
>               }
>         return m;
>        };
>        $(document).ready(function() {
>                document.cookie = "client_time=" + (+new Date());
>                $(".x").attr("href", "./answer/"+n($("p[id|='magic_number']").text()));
>        }); </script> </head> <body> <p> <a class="x" style="pointer-events: none;cursor: default;"
> href="http://54.75.225.110/quiz/answer/56595">this page</a> (be
> quick). </p>

为什么,“href”属性在哪里?

我使用BeautifulSoup 4测试了您的HTML代码:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html)

for a in soup.find_all('a'):
    if 'href' in a.attrs:
        print a['href']


http://54.75.225.110/quiz/answer/56595

您有拼写错误:

for item in soup.find_all(herf=True):
应该是href:

for item in soup.find_all(href=True):

请参阅。谢谢,您知道为什么我的代码没有显示“href”属性吗?不管怎样,它在我的电脑上还是不工作——我不明白这一点。我的输出是:嘿@PawelHuszcza不知道,可能是糟糕的HTML,或者只是
打印项
显示了一些东西different@PepperoniPizza
if
可以通过
soup.findAll('a',href=True)
来消除,我猜?经过修改后,它仍然不能做到这一点-它只显示:嘿,那里!:(我使用BeautifulSoup 4进行了测试,当
打印汤时得到的输出是什么?
?谢谢,我更正了它-但现在我得到的只是:嘿,还是不起作用。
for item in soup.find_all(href=True):