python 文件执行后没有输出_Python运行成功但是没有相应文件输出?

该博客主要讲述了在使用Python进行网络请求获取HTML内容并利用BeautifulSoup解析,提取股票信息的过程中,遇到文件无输出的问题。通过定义getHTMLText函数获取网页文本,getStockList函数抓取股票链接,getStockInfo函数解析股票信息并尝试写入文件。在main函数中调用这些函数执行整个流程。然而,可能存在因异常处理不当导致的数据写入失败的情况。
摘要由CSDN通过智能技术生成

def getHTMLText(url):

try:

r=requests.get(url,timeout=30)

r.raise_for_status()

r.encoding=r.apparent_encoding

return r.text

except:

return" "

>>> def getStockList(lst,stockURL):

html=getHTMLText(stockURL)

soup=BeautifulSoup(html,'html.parser')

StockList=soup.find('div',attrs={'class':'title'})

a=StockList.find_all('a')

for i in a:

try:

href=i.attrs['href']

lst.append(href)[0]

except:

continue

>>> def getStockInfo(lst,fpath):

for stock in lst:

html=getHTMLText(stock)

try:

if stock=="":

continue

infoDict={}

soup=BeautifulSoup(stock,'html.parser')

stockInfo=soup.find('div' ,attrs={'class’:’house-title'})

name=stockInfo.find_all('div',attrs={'class’:’wrapper'})[0]

infoDict.update({'房源名称':name.text.split()[0]})

with open(fpath,'a',encoding='utf-8')as f:

f.write(str(infoDict)+'\n')

except:

traceback.print_exc()

continue

>>> import requests

>>> from bs4 import BeautifulSoup

>>> import re

>>> import traceback

>>> def main():

stock_list_url='https://sz.lianjia.com/chengjiao/pg100/'

output_file='C://Users/Thinkpad/Desktop'

slist=[]

getStockList(slist,stock_list_url)

getStockInfo(slist,output_file)

>>> main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值