使用从BeautifulSoup网页抓取的网址

时间:2018-09-02 20:31:28

标签: python url beautifulsoup

按照标题,我已经刮了我感兴趣的网页,并将URL保存在一个变量中。

import requests
from bs4 import BeautifulSoup

for pagenumber in range(1, 2):
    url = 'https://www.congress.gov/search?q=%7B%22source%22%3A%22legislation%22%2C%22congress%22%3A%22112%22%7D&page={}'.format(pagenumber)
    res = requests.get(url, headers = {'User-agent': 'Chrome'})

soup = BeautifulSoup(res.text, 'html.parser')
lists = soup.find_all("li", {"class" : "expanded"})

for bill in lists:
    block = bill.find("span", {"class":"result-item"})
    link_cosponsors = block.find_all("a")[1]['href'] # I am interested in the second URL

最后一行是给我URL列表。现在,我正在努力访问每个URL,并从每个URL中抓取新信息。

for url in link_cosponsors:

    soup_cosponsor = BeautifulSoup(requests.get(url).text, 'html.parser')
    table = soup.find('table', {'class':'item_table'})

我认为问题在于link_cosponsors的创建方式,即列表的第一个元素不是完整的'https://etc'。但只有'h',因为我收到错误消息“无效的URL'h':未提供模式。也许您是说http://h?”。 我曾尝试将链接附加到列表中,但这也不起作用。

1 个答案:

答案 0 :(得分:2)

问题是您在for循环的每次迭代中都重新分配了link_cosponsors。这样,此变量将仅保留您找到的最后一个链接为字符串。

然后发生的是,您的for url in link_cosponsors逐个字母地对该字符串进行迭代。基本上是这样的:

for letter in 'http://the.link.you.want/foo/bar':
    print(letter)

解决方案:,您应该将第一个代码段的最后3行替换为:

link_cosponsors = []
for bill in lists:
    block = bill.find("span", {"class":"result-item"})
    link_cosponsors.append(block.find_all("a")[1]['href'])
相关问题