从多个div中选择要打印的url

2024-04-19 01:22:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程和Python的新手。你知道吗

我正在使用python2.7和BeautifulSoup从某个搜索结果页面提取所有url。你知道吗

页面是https://www.ohiobar.org/Pages/Find-a-Lawyer.aspx?sFN=&sLN=&sPA=&sCI=&sST=OH&sZC=(可能需要一段时间才能加载)

URL周围的代码如下如下所示:你知道吗

<div id="content_findResults">
<div id="content_column1">
<h1 id="ctl00_ctl45_g_1e68d58d_9902_48ce_b555_5d3eb35d5624_ctl00_headingCriteria">Showing Search Results for 'OH'</h1>
<h2 id="ctl00_ctl45_g_1e68d58d_9902_48ce_b555_5d3eb35d5624_ctl00_headingResults">Your search returned 18440 results</h2>
<h4 id="ctl00_ctl45_g_1e68d58d_9902_48ce_b555_5d3eb35d5624_ctl00_headingYourSearch">Your search: 'State: OH'</h4>

<ul id="ctl00_ctl45_g_1e68d58d_9902_48ce_b555_5d3eb35d5624_ctl00_resultsList">
<li>
<a href="**/Pages/MemberProfile.aspx?sST=OH&amp;pID=10727**">Janet Gilligan Abaray</a></li>
<li>
<a href="**/Pages/MemberProfile.aspx?sST=OH&amp;pID=26507**">Kenneth Pascal Abbarno</a></li>

我不知道该用什么来确保我可以从多个div,UL和LI中提取url。你知道吗

我正在使用以下命令:

def oh_crawler():
    url = "https://www.ohiobar.org/Pages/Find-a-Lawyer.aspx?sFN=&sLN=&sPA=&sCI=&sST=OH&sZC="
    code = requests.get(url)
    text = code.text
    soup = BeautifulSoup(text)
    for link in soup.find('div',{'id':'content_findResult', 'id':'content_column1'},'a'):
            href = 'https://www.ohiobar.org' + link.get('href')
            print (href)

很明显它不起作用。你知道吗

请告诉我如何选择网址打印。你知道吗


Tags: httpsdividurlwwwlipagescontent
1条回答
网友
1楼 · 发布于 2024-04-19 01:22:24

可以在href属性中获取包含MemberProfile的所有a元素:

from bs4 import BeautifulSoup
import requests

url = 'https://www.ohiobar.org/Pages/Find-a-Lawyer.aspx?sFN=&sLN=&sPA=&sCI=&sST=OH&sZC='

with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}

    response = session.get(url)
    soup = BeautifulSoup(response.content)

    for link in soup.select("div#content_findResults div#content_column1 ul li a[href*=MemberProfile]"):
        print link.get("href")

在这里,我使用CSS selector来定位a元素。你知道吗

印刷品:

/Pages/MemberProfile.aspx?sST=OH&pID=10727
/Pages/MemberProfile.aspx?sST=OH&pID=26507
...
/Pages/MemberProfile.aspx?sST=OH&pID=17139
/Pages/MemberProfile.aspx?sST=OH&pID=57207

相关问题 更多 >