python-3.x - 将列表传递给 requests.get()
问题描述
这将获取一个 URL 并以 XML 格式打印它。
import requests
from bs4 import BeautifulSoup
url = r'''https://secure.shippingapis.com/ShippingAPI.dll?API=Verify&XML=
<AddressValidateRequest USERID="564WILLC0589"><Address><Address1>
2451 Avalon Ct</Address1><Address2></Address2><City>Aurora</City>
<State>IL</State><Zip5></Zip5><Zip4></Zip4></Address></AddressValidateRequest>'''
#get the webpage
response = requests.get(url)
#see if the URL has been correctly encoded
r_url = response.text
#parse the downloaded page to get a beautifulsoup object
new_xml = BeautifulSoup(r_url, features = "xml").prettify()
print(new_xml)
# prints
>>>
<?xml version="1.0" encoding="utf-8"?>
<AddressValidateResponse>
<Address>
<Address2>
2001 GARDNER CIR W
</Address2>
<City>
AURORA
</City>
<State>
IL
</State>
<Zip5>
60503
</Zip5>
<Zip4>
6213
</Zip4>
</Address>
</AddressValidateResponse>
>>>
但是,我有一个需要以 XML 格式打印的 URL 列表。使用此列表,我如何一次将一个项目传递给 requests.get()?链接到文本文件。
#text file that has all the URLs
txtfile = r'C:\Users\jpilbeam\USPSAPIWCHDUpdateAll.txt'
#convert text file into a list
with open (txtfile) as f:
x = (list(map(str.strip ,f.readlines())))
解决方案
import requests
from bs4 import BeautifulSoup
# convert text file into a list
def file_to_list(file_name):
with open (file_name) as f:
return list(map(str.strip ,f.readlines()))
def scrape(url):
response = requests.get(url)
new_xml = BeautifulSoup(response.text, "html.parser")
print(new_xml)
txtfile = r'C:\Users\jpilbeam\USPSAPIWCHDUpdateAll.txt'
links = file_to_list(txtfile)
for link in links:
scrape(link )
推荐阅读
- django - 如何在 Django 中编写 sql COALESCE
- python-3.x - 为什么 cv2.VideoCapture(1) 需要四秒钟来检测运动?
- ios - 在 Google 地图自定义信息视图中显示 JSON 数据
- c - 在C语言中,如果我只是声明一个变量而不初始化它,编译器会为它保留空间吗?
- c++ - 如果 head 在 main 中本地声明,则链表的 void 递归反向函数的参数应该是什么?
- threadpool - 如何在 hystrix 线程池中找到活动线程的数量?
- javascript - 如何在 JavaScript 中返回父函数
- elixir - 在 Elixir 中,有没有办法使 _real_ 常量?
- java - 为什么我需要在下面的代码中使用 count -=1 ?
- arrays - 将数组划分为子数组,使它们的长度和 XOR 的乘积之和最小