python爬取a标签内href的⽅法及遇到的问题原博客地址:
1# -*- coding:utf-8 -*-
2#python 2.7
3#XiaoDeng
4#tieba.baidu/p/2460150866
5#标签操作
6
7
8from bs4 import BeautifulSoup
quest
10import re
11
12
13#如果是⽹址,可以⽤这个办法来读取⽹页
14#html_doc = "tieba.baidu/p/2460150866"
15#req = quest.Request(html_doc)
16#webpage = quest.urlopen(req)
17#html = ad()
18
19
20
21 html="""
22<html><head><title>The Dormouse's story</title></head>
23<body>
24<p class="title" name="dromouse"><b>The Dormouse's story</b></p>
25<p class="story">Once upon a time there were three little sisters; and their names were
26<a href="example/elsie" class="sister" id="xiaodeng"><!-- Elsie --></a>,
27<a href="example/lacie" class="sister" id="link2">Lacie</a> and
28<a href="example/tillie" class="sister" id="link3">Tillie</a>;
href标签怎么用29<a href="example/lacie" class="sister" id="xiaodeng">Lacie</a>
30and they lived at the bottom of a well.</p>
31<p class="story">...</p>
32"""
33 soup = BeautifulSoup(html, 'html.parser') #⽂档对象
34
35
36#查a标签,只会查出⼀个a标签
37#print(soup.a)#<a class="sister" href="example/elsie" id="xiaodeng"><!-- Elsie --></a>
38
39for k in soup.find_all('a'):
40print(k)
41print(k['class'])#查a标签的class属性
42print(k['id'])#查a标签的id值
43print(k['href'])#查a标签的href值
44print(k.string)#查a标签的string
('calss'),也可以达到这个效果
在使⽤该⽅法的k['href']读取⽹页链接时,编译器报错:
KeyError: 'href'
修改为:
<('href')
成功运⾏,取出href中的链接。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论