首页 > 解决方案 > 有没有一种简单的方法可以从文本文件读取到这个漂亮的汤库 python 脚本?

问题描述

如何将 txt.file 中的行读入此脚本,而不必在脚本中列出 url?谢谢

from bs4 import BeautifulSoup
import requests

url = "http://www.url1.com"

response = requests.get(url)

data = response.text

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

categories = soup.find_all("a", {"class":'navlabellink nvoffset nnormal'})

for category in categories:
    print(url + "," + category.text)

我的 text.file 内容有一个换行符的分隔符:

http://www.url1.com
http://www.url2.com
http://www.url3.com
http://www.url4.com
http://www.url5.com
http://www.url6.com
http://www.url7.com
http://www.url8.com
http://www.url9.com

标签: pythonbeautifulsouppython-requeststext-filesreadline

解决方案


file1 = open('text.file', 'r') 
Lines = file1.readlines() 

count = 0
# Strips the newline character 
for line in Lines: 
    print("Line{}: {}".format(count, line.strip())) 

你只需用 url 变量替换你的行


推荐阅读