Python爬虫第一课,选取标签内容

Python爬虫第一课,选取标签内容

  1. 获取标题`# from urllib.request import urlopen
  2. `# from urllib.error import HTTPError
  3. from bs4 import BeautifulSoup
  4. def getTitle(url):
  5. try: html = urlopen(url)
  6. except HTTPError as e:
  7. return None
  8. try:
  9. bsObj = BeautifulSoup(html.read())
  10. title = bsObj.body.h1
  11. except AttributeError as e:
  12. return None
  13. return title
  14. title = getTitle(“http://www.pythonscraping.com/pages/page1.html”)
  15. if title == None:
  16. print(“Title could not be found”)
  17. else:
  18. print(title)
  19. 获取标签特定问内容,get_text
  20. findAll(tag, attributes, recursive, text, limit, keywords)
    find(tag, attributes, recursive, text, keywords)
    .findAll({“h1”,“h2”,“h3”,“h4”,“h5”,“h6”})获取所有标签的所有内容
    .findAll(“span”, {“class”:{“green”, “red”}})获取指定标签指定内容
  21. recursive 设置为 True , findAll 就会根据你的要求去查找标签参数的所有子标签,如果 recursive 设置为 False , findAll 就只查找文档的一级标签,findAll默认是支持递归查找的( recursive 默认值是 True )。
  22. 范围限制参数 limit ,显然只用于 findAll 方法。 find 其实等价于 findAll 的 limit 等于1 时的情形。
  23. 还有一个关键词参数 keyword ,可以让你选择那些具有指定属性的标签。
    bsObj.findAll(id=“text”)等价于bsObj.findAll("", {“id”:“text”})
  24. ` from urllib.request import urlopen
  25. from bs4 import BeautifulSoup
  26. html = urlopen(“http://www.pythonscraping.com/pages/warandpeace.html”)
  27. bsObj = BeautifulSoup(html)
  28. list = bsObj.findAll(id = “text”)
  29. namelist = bsObj.findAll(“span”,{“class”:“green”})
  30. for name in namelist :
  31. print(name.get_text())
    
  32. for a in list :
  33. print(a.get_text())`
    
  34. 分享就到这里!本文内容提取自Python网络采集!
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值