【问题标题】:Deleting anything but plain Text in python在python中删除纯文本以外的任何内容
【发布时间】:2019-01-24 07:52:38
【问题描述】:

我试图让代码只获取<p> 标签之间的所有内容。我还没有找到方法。

我尝试使用一个简单的循环,这个程序你应该输入一个 url,当你运行它时会显示纯文本。

    import urllib.request
    import urllib.parse
    import re

    print("Enter the URL")
    url = input()

    #url = "https://en.wikipedia.org/wiki/Somalia"
    values = {'s':'basic', 'submit':'search'}
    data = urllib.parse.urlencode(values)
    data = data.encode('utf-8')
    req = urllib.request.Request(url,data)
    resp = urllib.request.urlopen(req)
    respData = resp.read()

    #print(respData)

    paragraphs = re.findall(r'<p>(.*?)</p>', str(respData))

    for eachP in paragraphs:
        print(eachP)

我也尝试过使用 BeutifulSoup,但还没有成功导入。

【问题讨论】:

标签: python urllib


【解决方案1】:

欢迎来到 SO 和编程。 You can't parse [X]HTML with regex. 是时候使用库了。 Beautiful Soup 和你的requests 是你这里最好的朋友。

在您的 bash/cmd/终端类型中:

pip install requests
pip install beautifulsoup4

然后使用:

import requests
from bs4 import BeautifulSoup


r = requests.get("https://en.wikipedia.org/wiki/Somalia")
soup = BeautifulSoup(r.text) # you need to define the parser but for now its ok.
for p in soup.find_all('p'):
    print(p.text)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 2015-05-03
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多