Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 遍历URL列表并获取选定文本_Python_Beautifulsoup - Fatal编程技术网

Python 遍历URL列表并获取选定文本

Python 遍历URL列表并获取选定文本,python,beautifulsoup,Python,Beautifulsoup,您好,我正在尝试编写一个脚本,该脚本将从URL列表(在本例中为工作列表)中提取指定信息,然后使用每个工作列表页面上的指定信息(来自html)将其写入文件。关于写入一个我现在不太关心的文件的部分,我更关注的是能够从指定的链接中提取所需的信息。我编写此代码是为了创建感兴趣的URL列表: import requests from bs4 import BeautifulSoup # Get links for all open listings mainpage = requests.get('ht

您好,我正在尝试编写一个脚本,该脚本将从URL列表(在本例中为工作列表)中提取指定信息,然后使用每个工作列表页面上的指定信息(来自html)将其写入文件。关于写入一个我现在不太关心的文件的部分,我更关注的是能够从指定的链接中提取所需的信息。我编写此代码是为了创建感兴趣的URL列表:

import requests
from bs4 import BeautifulSoup

# Get links for all open listings
mainpage = requests.get('https://www.digitalmarketplace.service.gov.uk/digital-outcomes-and-specialists/opportunities?q=&statusOpenClosed=open%27%27%27')
soup = BeautifulSoup(mainpage.text, 'html.parser')
link_list = []

for opps in soup.findAll('li', class_='app-search-result'):
    links = opps.h2.a.get('href')
    open_links = ('https://www.digitalmarketplace.service.gov.uk/%27+links')
    link_list.append(open_links)
# print(link_list[25])
这很好,因为我可以通过索引选择所需的链接。在下一部分中,我将尝试编写一个For循环,该循环将遍历link_列表中的每个链接,然后获取相应链接的指定信息

# Write for loop hat grabs specified information
for idx, item in enumerate(link_list[0:]):
    open_opps = requests.get(open_links)
    open_soup = BeautifulSoup(open_opps.text, 'html.parser')
    closing_date = open_soup.findAll(class_="govuk-summary-listvalue")[2].text
    summary = open_soup.findAll(class_="govuk-summary-listvalue")[3].text

print(closing_date[25])
在上面的代码中,我试图提取第24份工作清单的截止日期,但收到一个错误:

closing_date = open_soup.findAll(class_="govuk-summary-listvalue")[2].text
IndexError: list index out of range

我想知道我如何写这篇文章,这样我就可以提取指定的信息,如第二份工作清单的截止日期。如果您在解析截止日期时使用了错误的xpath类,我们将非常感谢您的帮助

 closing_date = open_soup.findAll(class_="govuk-summary-list__value")[2].text
 summary = open_soup.findAll(class_="govuk-summary-list__value")[3].text

使用
govuk-summary-list\u值作为类值,而不是
govuk-summary-list\u值

列表索引从0开始,因此如果您想要第二份工作列表的截止日期,则需要使用索引1。提示:当您遇到“IndexError:list index out range”(索引器:列表索引超出范围)时,打印列表和索引以查看出了什么问题可能会很有用(在这种情况下,不需要打印索引,因为它是一个常量)。很抱歉,我没有提到截止日期的索引,摘要等同于他们页面html中标记的索引。因此,在工作列表页面的html中有多个“govuk summary listvalue”类
https://www.digitalmarketplace.service.gov.uk/%27+链接“
此url无效您必须使用c字符串格式或f字符串格式,例如:
”https://www.digitalmarketplace.service.gov.uk{}.格式(链接)