python中的requests.get(url)在循环中使用时表现不同

问题描述 投票:0回答:1

我是python编程的新手,正在尝试抓取Urls.txt文件中的所有可用链接。我写的代码是:

import requests
from bs4 import BeautifulSoup
from fake_useragent import UserAgent
user_agent = UserAgent()
fp = open("Urls.txt", "r")
values = fp.readlines()
fin = open("soup.html", "a")
for link in values:
    print( link )
    page = requests.get(link, headers={"user-agent": user_agent.chrome})
    html = page.content
    soup = BeautifulSoup(html, "html.parser")
    fin.write(str(soup))

当链接以字符串形式而不是变量形式直接提供时,代码工作得很好,但是当使用时,输出会有所不同。

python web-scraping xml-parsing python-requests html-parsing
1个回答
0
投票

也许您从文件中读取的字符串有换行符。要删除它,请使用link.strip("\n")

© www.soinside.com 2019 - 2024. All rights reserved.