URL库请求.urlopen(url).read()与SQLAlchemy一起存储的是十六进制字符串而不是HTML

2024-05-19 21:14:36 发布

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

我正在尝试使用urllibSQLAlchemy在postgres中存储一些HTML,但是在插入/检索HTML的过程中似乎有些东西被弄错了

使用:SQLAlchemy 1.2、Python 3.6、postgres 10、urllib

class ParksTxState(Base):
    __tablename__ = 'parks_tx_state'

    id = Column(Integer, primary_key=True)
    park_name = Column(Text)
    url = Column(Text)
    html = Column(Text)


engine = create_engine("postgresql://<user>:<pass>@localhost/<db>", echo=False)

Session = sessionmaker(bind=engine)
session = Session()

url = 'https://tpwd.texas.gov/state-parks/abilene'
html = request.urlopen(url).read()

print(html)
# b'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n...
# so far so good...

newpark = ParksTxState()
newpark.html = html

print(newpark.html)
# b'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n...
# so we're still good here before committing....

session.add(newpark)
session.commit()

print(newpark.html)
# \x3c21444f43545950452068746d6c3e0a3...
# and here is where the garbage comes in.

由于某些原因,HTML被存储为一个长字符串。。 \x3c21444f43545950452068746d6c3e0a3c68746d6c20786d6c6e733d22687474703a2f2f7777772e7...

我甚至设置了echo=True,并看到insert语句是正确的。你知道吗

我做错什么了?你知道吗


Tags: texturlsosqlalchemysessionhtmlcolumnpostgres