【问题标题】:Python BeautifulSoup extracting text from resultPython BeautifulSoup 从结果中提取文本
【发布时间】:2016-12-27 12:53:24
【问题描述】:

我正在尝试从内容中获取文本,但是当我在结果变量上尝试漂亮的汤函数时,它会导致错误。

from bs4 import BeautifulSoup as bs
import requests

webpage = 'http://www.dictionary.com/browse/coypu'
r = requests.get(webpage)
page_text = r.text

soup = bs(page_text, 'html.parser')

result = soup.find_all('meta', attrs={'name':'description'})  

print (result.get['contents'])

我正在尝试读取结果;

“海狸鼠的定义,一种大型的南美水生啮齿动物,Myocastor(或 Myopotamus)海狸鼠,产生毛皮海狸鼠。查看更多信息。”

【问题讨论】:

  • result.get('contents') 也许?
  • 你在result.get中有问题,应该使用result[0].get("content"),你正在使用“contents”。

标签: python regex beautifulsoup


【解决方案1】:

soup.find_all() 返回一个列表。由于在您的情况下,它只返回列表中的一个元素,您可以这样做:

>>> type(result)
<class 'bs4.element.ResultSet'>
>>> type(result[0])
<class 'bs4.element.ResultSet'>
>>> result[0].get('content')
Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more.

【讨论】:

    【解决方案2】:

    当你只希望第一个或单个标签使用find时,find_all 返回一个list/resultSet

    result = soup.find('meta', attrs={'name':'description'})["contents"]
    

    您还可以将 css 选择器select_one 一起使用:

    result = soup.select_one('meta[name=description]')["contents"]
    

    【讨论】:

      【解决方案3】:

      您不需要使用 findall,因为只有使用 find 才能获得所需的输出'

      from bs4 import BeautifulSoup as bs
      import requests
      
      webpage = 'http://www.dictionary.com/browse/coypu'
      r = requests.get(webpage)
      page_text = r.text
      
      soup = bs(page_text, 'html.parser')
      
      result = soup.find('meta', {'name':'description'})
      
      print result.get('content')
      

      它会打印出来:

      Coypu definition, a large, South American, aquatic rodent, Myocastor (or Myopotamus) coypus, yielding the fur nutria. See more.
      

      【讨论】:

      • 我在您的前一天添加的答案中是否尚未涵盖 find
      • 我错过了,很抱歉,因为我查看了问题和他的代码并编写了我的代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多