【问题标题】:How to search Dictionary.com for a word and ONLY extract the first definition?如何在 Dictionary.com 中搜索一个单词并仅提取第一个定义?
【发布时间】:2022-01-12 03:34:00
【问题描述】:

这是我的代码:

import colored
import requests
from bs4 import BeautifulSoup

inputcolor = colored.fg(2)

headers = {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': 'GET',
    'Access-Control-Allow-Headers': 'Content-Type',
    'Access-Control-Max-Age': '3600',
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'
    }

url = "https://www.dictionary.com/browse/balance-of-power"
req = requests.get(url, headers)
soup = BeautifulSoup(req.content, 'html.parser')
print(soup.find_all("div", {"value": "1"}))

我之所以使用soup.find_all("div", {"value": "1"}),是因为这是站点代码中第一个结果的位置:

<div value="1" class="css-10ul8x e1q3nk1v2"><span class="one-click-content css-nnyc96 e1q3nk1v1" data-term="distribution" data-linkid="nn1ov4">a distribution and opposition of forces among nations such that no single nation is strong enough to assert its will or dominate all the others.</span></div>

我的代码返回这个:

<div value="1" class="css-10ul8x e1q3nk1v2"><span class="one-click-content css-nnyc96 e1q3nk1v1" data-term="distribution" data-linkid="nn1ov4">a distribution and opposition of forces among nations such that no single nation is strong enough to assert its will or dominate all the others.</span></div>

它很接近,但它仍然不只打印定义而没有其他任何东西,我怎么能让它做到这一点?

【问题讨论】:

  • soup.find_all("div", {"value": "1"})[0].get_text() 呢?
  • 成功了,非常感谢。不完全确定它为什么起作用,但你让它起作用了
  • @RJAdriaansen,为什么不把它作为一个答案,这是一个常见的问题?
  • 等一下
  • @gfdgfdgdf 如果您不知道为什么会起作用,请查看:crummy.com/software/BeautifulSoup/bs4/doc/#get-text

标签: python html css beautifulsoup python-requests


【解决方案1】:

find_all 返回一个列表。因此,您必须通过索引0 获取第一个列表项。然后就可以用get_text()提取文字了:

soup.find_all("div", {"value": "1"})[0].get_text()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-17
    • 2023-01-12
    相关资源
    最近更新 更多