用靓汤拉屎的时候会有奇怪的人物

2024-05-19 18:19:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从eshop网站返回html作为一个字符串,但得到一些奇怪的字符。当我查看webconsole时,在html中没有看到这些字符。当html显示在jupyter笔记本的熊猫数据框中时,我也看不到这些字符。链接是https://www.powerhousefilms.co.uk/collections/limited-editions/products/immaculate-conception-le。我也使用相同的方法在这个网站上的另一个产品,但只看到这些字符在这一页。站点中的其他页面不存在此问题。在

html = requests.get(url).text
soup = BeautifulSoup(html)
elem = soup.find_all('div', {'class': product-single_description rte'})
s = str(elem[0])

s看起来像:

^{pr2}$

我尝试过指定编码,但仍然得到奇怪的字符。对于这个网站上的50多个产品,只有少数有这个问题。在

我刮擦的方式有问题吗?或者可能有一个简单的方法来清理这个问题。在

谢谢


Tags: 数据方法字符串https产品网站链接html
2条回答

所以结果是excel造成的。当我保存到CSV并在excel中打开时,我得到了奇怪的结果。在

为了防止这种情况,我使用了df.to_csv('df.csv', index=False, encoding = 'utf-8-sig')。指定编码可以消除奇怪的字符。在

Python Writing Weird Unicode to CSV有一些关于编码和excel如何穿透csv文件的信息。在

使用这段代码下载网页中的可见内容。 只需在网页上输入网址

from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import os


page_url = "URL Here"
def tag_visible(element):
    if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
        return False
    if isinstance(element, Comment):
        return False
    return True


def text_from_html(body):
    soup = BeautifulSoup(body, 'html.parser')
    texts = soup.findAll(text=True)
    visible_texts = filter(tag_visible, texts)
    return u" ".join(t.strip() for t in visible_texts)

def Extract_Text(html_bytes, url):
    text_data = text_from_html(html_bytes)
    f = open("DOC.txt", "w")
    string = str(url) + "\n" + text_data
    f.write(str(string))
    f.close()

html_string = ''
response = urlopen(page_url)
if 'text/html' in response.getheader('Content-Type'):
    html_bytes = response.read()
    html_string = html_bytes.decode("utf-8")
Extract_Text(html_bytes, page_url)

相关问题 更多 >