鱼C论坛

 找回密码
 立即注册
查看: 1535|回复: 3

[已解决]为何soup.find()无法找到<td></td>标签?

[复制链接]
发表于 2017-10-21 14:42:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. import requests
  2. import bs4

  3. hd = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
  4. res = requests.get('http://sc.hkexnews.hk/TuniS/www.hkexnews.hk/sdw/search/mutualmarket_c.aspx?t=hk',headers = hd)
  5. html = res.text
  6. soup = bs4.BeautifulSoup(html,'html.parser')
  7. soup.prettify()
  8. node = soup.find('td',attrs = {'class':'arial12black'},string = '长和')
  9. print(node)
复制代码

运行结果为None,为何找不到含有字符串"长和"的td标签?
最佳答案
2017-10-21 17:00:17
  1. >>> a
  2. <td class="arial12black" valign="top">

  3.                                 长和

  4.                             </td>
  5. >>> b=str(a)
  6. >>> b
  7. '<td class="arial12black" valign="top">\r\n                                长和\r\n                            </td>'
复制代码


  1. import requests
  2. import bs4
  3. import re

  4. hd = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
  5. res = requests.get('http://sc.hkexnews.hk/TuniS/www.hkexnews.hk/sdw/search/mutualmarket_c.aspx?t=hk',headers = hd)
  6. html = res.text
  7. soup = bs4.BeautifulSoup(html,'html.parser')
  8. soup.prettify()
  9. node = soup.find('td',attrs = {'class':'arial12black'},string = re.compile('长和'))
  10. print(node)

复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2017-10-21 17:00:17 | 显示全部楼层    本楼为最佳答案   
  1. >>> a
  2. <td class="arial12black" valign="top">

  3.                                 长和

  4.                             </td>
  5. >>> b=str(a)
  6. >>> b
  7. '<td class="arial12black" valign="top">\r\n                                长和\r\n                            </td>'
复制代码


  1. import requests
  2. import bs4
  3. import re

  4. hd = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
  5. res = requests.get('http://sc.hkexnews.hk/TuniS/www.hkexnews.hk/sdw/search/mutualmarket_c.aspx?t=hk',headers = hd)
  6. html = res.text
  7. soup = bs4.BeautifulSoup(html,'html.parser')
  8. soup.prettify()
  9. node = soup.find('td',attrs = {'class':'arial12black'},string = re.compile('长和'))
  10. print(node)

复制代码
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2017-10-23 14:36:50 | 显示全部楼层

请问高手,为什么要用正则表达式去匹配,是不是字符串里面含有空格?
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2017-10-23 17:22:24 | 显示全部楼层
John2430 发表于 2017-10-23 14:36
请问高手,为什么要用正则表达式去匹配,是不是字符串里面含有空格?

我猜如果填字符串而不是正则表达式的话需要完全匹配才会返回结果,我学bs不是很久,不是很清楚它的匹配机制
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-4 22:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表