使用python从网页中提取特定的文本。

问题描述 投票:0回答:1

以下网址中的 "单词 "选项卡显示了我在Duolingo的阿拉伯语课程中可用的单词。

https:/duome.eutheahmedmustafaprogress。

我已经学过的单词是用粗蓝的颜色,其他的是用普通字体。

我想用一个方法(最好是Python或Java)来提取我已经学会的单词。我试着使用Python请求来访问页面的源代码,并从那里开始工作,但它似乎不包含任何信息,可以用来从其他单词中筛选出所学的单词。

任何帮助将被感激!

图片。页面的快照

python web-scraping
1个回答
1
投票

这个脚本应该打印所有粗体字从你的页面。

import re
import requests
from bs4 import BeautifulSoup

cookie_url = 'https://duome.eu/tz.php?time=GMT%202'
vocabulary_url = 'https://duome.eu/vocabulary/en/ar/{user_id}'
url = 'https://duome.eu/theahmedmustafa/progress'

with requests.session() as s:
    s.get(cookie_url).text  # load cookies
    html_data = s.get(url).text
    user_id = re.search(r'/vocabulary/en/ar/(\d+)', html_data).group(1)
    soup = BeautifulSoup(s.get(vocabulary_url.format(user_id=user_id)).text, 'html.parser')
    for a in soup.select('#words li > b > a'):
        print(a.text)

这个可以打印:

أَرْوى
أَلْمانْيا
أَمريكا
أَمريكِيّ
أَمْريكِيّة
أَمْسْتِرْدام
أَنا
أَنْتَ
أَنْتِ
أَهْلاً
أَيْن
أُرْدُنِيّ
أُرْدُنِيّة
أُسْتاذ
أُسْتُرالْيا
إِسْكُتْلَنْدا
إِسْكُتْلَنْدِيّ
إِسْلامِيّة
إِنْجِليزِيّ
إِنْجِلْتِرا
امْرَأة
اِمْرَأة
باب
باريس

... and so on.

2
投票

正如你所说,这是正确的,这是 "Web Scraping",而python有惊人的模块。最明显的一个是-&gt。BeautifulSoup

所以,要从你的网页上获取信息。

  • 你需要先了解网页的结构。
  • 另外,在某些情况下,这可能不完全合法。
  • 更大的挑战是,网页是否支持搜刮功能?
    • 这可以通过查看网页的源代码来解决。
    • 如果你想抓取的文本信息可以在源文件或其中一个hrefs中查看,那么就可以使用Beautifulsoup来抓取它。

解决方法---------------------。

  • 在你得出解决方案之前,你必须了解HTML结构和你可以识别网页上任何元素的方法。
  • 方法有很多,比如

    • 使用网页上任何元素的 "id"。
    • 直接使用类或tagname
    • 使用元素的xpath
    • 或上述任何一项或全部内容的组合。
  • 一旦你到了这个地步,现在你一定清楚了我们要继续前进的方向

#make a request to the webpage, and grab the html respone
page = requests.get("your url here").content

#pass it on to beautifulsoup 
from bs4 import BeautifulSoup
soup = BeautifulSoup(page.content, 'html.parser')

#Depending on how you want to find, you can use  findbyclass, findbytag, and #other methods 
soup.findAll('your tag')
© www.soinside.com 2019 - 2024. All rights reserved.