【问题标题】:Cant get list of definitions from a website using a for loop无法使用 for 循环从网站获取定义列表
【发布时间】:2020-04-01 09:26:38
【问题描述】:

这里是python的新手。我正在尝试获取当天的词汇以及定义和“你知道吗?”这里的部分https://www.merriam-webster.com/word-of-the-day

知道我错过了什么吗?

到目前为止,我能得到的只有以下内容:

C:\Users\Think\PycharmProjects\wotd\venv\Scripts\python.exe C:/Users/Think/PycharmProjects/wotd/wotd.py
loon
Definition
1 : lout, idler

loon 是单词,后面的行仅是第一个定义。还有3个,但我不能用这种方法得到它们。

感谢您的指导

    from bs4 import BeautifulSoup
import requests

sauce = requests.get('https://www.merriam-webster.com/word-of-the-day').text

soup = BeautifulSoup(sauce, 'lxml')

article = soup.find('article')

word = article.find('div', class_='word-and-pronunciation').h1.text
definition = article.find('div', class_='wod-definition-container').h2.text

print(word)
print(definition)

for article in soup.find_all('article'):
    defin = article.find('div', class_='wod-definition-container').p.text
    print(defin)

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    article.find('div', class_='wod-definition-container').p.text 只返回拳头

    。试试这样。

    for s in soup.find_all('article')[0].find('div', class_='wod-definition-container').find_all('p'):
        print(s.text)
    

    【讨论】:

    • 谢谢 shimo,这行得通,我明白了为什么 :) 现在的输出给了我所有的定义以及“你知道吗?”之后的文字。和其他一些不相关的文字。如果我只想要定义,如何限制 for 循环可以走多远?有时有 2 个定义,有时有 5 个。有没有办法让它停在最后一个定义处?
    • 我不确定页面的结构是否良好,但如果我确定了,请在每个 for 循环中检查 if str(num) + " : " in s.text 和 num += 1。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2023-02-09
    • 2019-09-18
    • 2013-04-24
    相关资源
    最近更新 更多