Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的美化组链接属性_Python_Web Scraping_Beautifulsoup_Findall - Fatal编程技术网

Python中的美化组链接属性

Python中的美化组链接属性,python,web-scraping,beautifulsoup,findall,Python,Web Scraping,Beautifulsoup,Findall,我在探索BeautifulSoup时引用了Ryan Mitchell的“用Python抓取网页” 有一些示例代码解释了如何从维基百科中删除文章链接。为了简洁起见,我省略了导入代码。代码是: html = urlopen("http://en.wikipedia.org") bsObj = BeautifulSoup(html) for link in bsObj.findAll("a", href = re.compile("^(/wiki/)

我在探索BeautifulSoup时引用了Ryan Mitchell的“用Python抓取网页”

有一些示例代码解释了如何从维基百科中删除文章链接。为了简洁起见,我省略了导入代码。代码是:

html = urlopen("http://en.wikipedia.org")
bsObj = BeautifulSoup(html)

for link in bsObj.findAll("a", href = re.compile("^(/wiki/)((?!:).)*$")):
     if 'href' in link.attrs:
          print(link.attrs['href'])
我不明白为什么代码需要包含if语句:

if 'href' in link.attrs:
findAll函数不是返回所有具有指定href的锚标记吗?因此,假设所有的“链接”都有“href”作为属性,这不是很好吗?
提前谢谢你

因为从此行返回

for link in bsObj.findAll("a", href = re.compile("^(/wiki/)((?!:).)*$")):
不仅是“href”,还有任何其他属性


因此,如果link.attrs中的'href'出现这一行:为了确保您只获得attribute'href'

您的想法是有效的,但是尝试尝试添加一个else语句并在else语句中打印link.attrs,看看是否有任何链接没有href属性,这永远不会出现,但您永远不会知道,祝你好运。

你得到的确切错误是什么?您是否试图在终端上打印错误?您无法确定
a
标记是否有链接(href attribute)。这就是测试的目的(
如果link.attrs:…
中的'href')。首先测试属性中是否有
href
,如果有,则打印该值。