Python:BeautifulSoup将HTML段落标记中的单词添加到列表中

Python:BeautifulSoup将HTML段落标记中的单词添加到列表中,python,beautifulsoup,Python,Beautifulsoup,我一直在努力学习与BeautifulSoup网站刮。我正在尝试制作一个Hangman游戏来学习Python,并希望制作一个单人模式,使用英语中最常用的1000个单词。我最初只是打算复制粘贴每个单词并运行一个列表(这就是为什么会有while循环),但我决定尝试使用BeautifulSoup import requests from bs4 import BeautifulSoup #words = [] #while True: #word = input("Enter the word

我一直在努力学习与BeautifulSoup网站刮。我正在尝试制作一个Hangman游戏来学习Python,并希望制作一个单人模式,使用英语中最常用的1000个单词。我最初只是打算复制粘贴每个单词并运行一个列表(这就是为什么会有while循环),但我决定尝试使用BeautifulSoup

import requests
from bs4 import BeautifulSoup

#words = []
#while True:
    #word = input("Enter the word: ")
    #words.append(word)
    #print(words)

page = requests.get("https://www.ef.edu/english-resources/english-vocabulary/top-1000-words/") 
resources/english-vocabulary/top-1000-words/")
soup = BeautifulSoup(page.content, "html.parser")
para = soup.find(class_="field-item even")

我不太确定从这里到哪里去。我试图将网站上的所有项目(位于feild item偶数类第二段标记中)分别添加到一个列表中,然后将该列表保存为一个包,以便在主刽子手游戏中使用。因为这些词出现在第二段标签中,我不知道该怎么做。我看了一些YouTube视频,但它们都处理有id或其他类可供调用的文本。谢谢

单词在第二个
中,所以使用
段落。查找所有(“p”)[1]
来获取它

然后你可以从这个标签中获得
.text
——它将所有的单词都放在一个字符串中

字符串中有一些选项卡,您应该删除它们-
。替换(“\t”,”)
,然后您可以
。拆分(“\n”)
来创建包含单词的列表

import requests
from bs4 import BeautifulSoup

page = requests.get("https://www.ef.edu/english-resources/english-vocabulary/top-1000-words/") 

soup = BeautifulSoup(page.content, "html.parser")
para = soup.find(class_="field-item even")

second_p = para.find_all('p')[1]
text = second_p.text.replace('\t', '')
words = text.split('\n')
print(words)

我为你写了一个快速的解决方案。您只需要找到正确的div,然后选择包含单词的正确子标记。由于格式的原因,单词需要去掉空白并放在列表中。更详细地描述了该过程

import requests
from bs4 import BeautifulSoup

class Hangman:

    def run_game(self):
        word_bank = self.get_word_bank()
        while True:
            # Your game here

    def get_word_bank(self):
        page = requests.get("https://www.ef.edu/english-resources/english-vocabulary/top-1000-words/", verify=False)
        soup = BeautifulSoup(page.content, "html.parser")
        words_tag = soup.find('div', {'class': "field-item even"})
        word_bank = words.split(", ".join(words_tag.findChildren()[1].getText().split()))
        return word_bank

if __name__ == "__main__":
    hangman = Hangman()
    hangman.run_game()

链接被一分为二吗?