python - 从多个 DIV 选择要打印的 URL

标签 python python-2.7 web-scraping beautifulsoup html-parsing

我是编程和 Python 新手。

我使用 Python 2.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 中提取 UR。

我正在使用以下内容:

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)

显然它不起作用。

请告知我如何选择要打印的 URL。

最佳答案

您可以获取 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

关于python - 从多个 DIV 选择要打印的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30156492/

相关文章:

r - 在 Yahoo! 中抓取关键统计数据用 R 理财

python - 如何对 4D numpy 数组执行迭代 2D 操作

python - 不理解 model.getAttr() 的参数

python - 为什么 is_(a,b) 函数在 python 2.7.3 中比 eq(a,b) 运行得更快?

python - Scrapy不抓取下一页url

node.js - 关于简单命令行网络爬虫(Clojure/ClojureScript)的一些问题

python - 如何从一个列表中获取一个值并将其应用于另一列表中的所有值

python - 使用 TensorFlow 对实时视频进行分类

python - 一段时间后 POSTGIS 插入变慢

python - 计算积分的有效方法?