【问题标题】:Web scraping with Beautiful Soup gives empty ResultSet使用 Beautiful Soup 进行 Web 抓取会给出空的 ResultSet
【发布时间】:2017-05-24 16:55:18
【问题描述】:

我正在尝试使用 Beautiful Soup,并尝试从包含以下类型片段的 HTML 文档中提取信息:

<div class="entity-body">
<h3 class="entity-name with-profile">
<a href="https://www.linkedin.com/profile/view?id=AA4AAAAC9qXUBMuA3-txf-cKOPsYZZ0TbWJkhgfxfpY&amp;trk=manage_invitations_profile" 
data-li-url="/profile/mini-profile-with-connections?_ed=0_3fIDL9gCh6b5R-c9s4-e_B&amp;trk=manage_invitations_miniprofile" 
class="miniprofile" 
aria-label="View profile for Ivan Grigorov">
<span>Ivan Grigorov</span>
</a>
</h3>
<p class="entity-subheader">
Teacher
</p>
</div>

我使用了以下命令:

with open("C:\Users\pv\MyFiles\HTML\Invites.html","r") as Invites: soup = bs(Invites, 'lxml')
soup.title
out: <title>Sent Invites\n| LinkedIn\n</title>
invites = soup.find_all("div", class_ = "entity-body")
type(invites)
out: bs4.element.ResultSet
len(invites)
out: 0

为什么 find_all 返回空的 ResultSet 对象?

您的建议将不胜感激。

【问题讨论】:

  • 在获取页面时尝试查看页面。如果你在那里看不到这个div标签,这意味着这部分是使用JS生成的,所以你不能这样刮(你必须使用selenium)。

标签: python beautifulsoup resultset findall


【解决方案1】:

问题是文档没有被读取,它只是一个TextIOWrapper (Python 3) 或File(Python 2) 对象。你必须阅读文档并传递标记,本质上是一个stringBeautifulSoup

正确的代码是:

with open("C:\Users\pv\MyFiles\HTML\Invites.html", "r") as Invites:
    soup = BeautifulSoup(Invites.read(), "html.parser")
    soup.title
    invites = soup.find_all("div", class_="entity-body")
    len(invites)

【讨论】:

  • 我按照你的建议更改了代码,但我仍然得到 len(invites) 为 0。
  • 我得到 1。也许添加一个 printstatement:print(len(invites))(Python 3) 或 print len(invites) (Python 2)。
【解决方案2】:
import bs4

html = '''<div class="entity-body">
<h3 class="entity-name with-profile">
<a href="https://www.linkedin.com/profile/view?id=AA4AAAAC9qXUBMuA3-txf-cKOPsYZZ0TbWJkhgfxfpY&amp;trk=manage_invitations_profile" 
data-li-url="/profile/mini-profile-with-connections?_ed=0_3fIDL9gCh6b5R-c9s4-e_B&amp;trk=manage_invitations_miniprofile" 
class="miniprofile" 
aria-label="View profile for Ivan Grigorov">
<span>Ivan Grigorov</span>
</a>
</h3>
<p class="entity-subheader">
Teacher
</p>
</div>'''

soup = bs4.BeautifulSoup(html, 'lxml')
invites = soup.find_all("div", class_ = "entity-body")
len(invites)

出来:

1

这段代码运行良好

【讨论】:

  • 那么问题出在读取html页面并将其转换为soup对象的语句上。这很奇怪,因为我从一本书中复制了这种语法,并用另一个 html 页面对其进行了测试。 html 页面是由 Chrome 在右键单击浏览器中打开的网页时通过 Save as... 命令生成的。出了什么问题?
  • @gk7 能否提供该页面的完整 HTML 代码或 URL
  • @gk7 我得到了 404。
  • 如果您是linkedin用户,您必须登录并使用此地址将获得您受邀与您联系但目前尚未回复的人。您可以通过发送一些邀请来试验此功能——如果它是空的。
  • @gk7 抱歉,我无法为您提供此类限制信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
相关资源
最近更新 更多