我在python中编写了一个脚本,以获取不同的链接,从而导致网页上的不同文章.在运行我的脚本后,我可以完美地获得它们.但是,我面临的问题是文章链接遍历多个页面,因为它们是大数字以适合单个页面.如果我点击下一页按钮,我可以在开发人员工具中看到附加的信息,这实际上是通过帖子请求产生一个ajax调用.由于下一页按钮没有附加链接,我找不到任何方法继续下一页并从那里解析链接.我试过用它post request
,formdata
但它似乎没有用.我哪里错了?
这是我点击下一页按钮时使用chrome dev工具获得的信息:
GENERAL
=======================================================
Request URL: https://www.ncbi.nlm.nih.gov/pubmed/
Request Method: POST
Status Code: 200 OK
Remote Address: 130.14.29.110:443
Referrer Policy: origin-when-cross-origin
RESPONSE HEADERS
=======================================================
Cache-Control: private
Connection: Keep-Alive
Content-Encoding: gzip
Content-Security-Policy: upgrade-insecure-requests
Content-Type: text/html; charset=UTF-8
Date: Fri, 29 Jun 2018 10:27:42 GMT
Keep-Alive: timeout=1, max=9
NCBI-PHID: 396E3400B36089610000000000C6005E.m_12.03.m_8
NCBI-SID: CE8C479DB3510951_0083SID
Referrer-Policy: origin-when-cross-origin
Server: Apache
Set-Cookie: ncbi_sid=CE8C479DB3510951_0083SID; domain=.nih.gov; path=/; expires=Sat, 29 Jun 2019 10:27:42 GMT
Set-Cookie: WebEnv=1Jqk9ZOlyZSMGjHikFxNDsJ_ObuK0OxHkidgMrx8vWy2g9zqu8wopb8_D9qXGsLJQ9mdylAaDMA_T-tvHJ40Sq_FODOo33__T-tAH%40CE8C479DB3510951_0083SID; domain=.nlm.nih.gov; path=/; expires=Fri, 29 Jun 2018 18:27:42 GMT
Strict-Transport-Security: …
Run Code Online (Sandbox Code Playgroud) 我想从html文档中提取某些信息.例如,它包含一个表(在其他表中包含其他内容),如下所示:
<table class="details">
<tr>
<th>Advisory:</th>
<td>RHBA-2013:0947-1</td>
</tr>
<tr>
<th>Type:</th>
<td>Bug Fix Advisory</td>
</tr>
<tr>
<th>Severity:</th>
<td>N/A</td>
</tr>
<tr>
<th>Issued on:</th>
<td>2013-06-13</td>
</tr>
<tr>
<th>Last updated on:</th>
<td>2013-06-13</td>
</tr>
<tr>
<th valign="top">Affected Products:</th>
<td><a href="#Red Hat Enterprise Linux ELS (v. 4)">Red Hat Enterprise Linux ELS (v. 4)</a></td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
我想提取信息,如"发布日期:".看起来像BeautifulSoup4可以轻松地做到这一点,但不知何故,我无法做到这一点.我的代码到目前为止:
from bs4 import BeautifulSoup
soup=BeautifulSoup(unicodestring_containing_the_entire_htlm_doc)
table_tag=soup.table
if table_tag['class'] == ['details']:
print table_tag.tr.th.get_text() + " " + table_tag.tr.td.get_text()
a=table_tag.next_sibling
print unicode(a)
print table_tag.contents
Run Code Online (Sandbox Code Playgroud)
这将获取第一个表行的内容,以及内容列表.但是下一个兄弟的事情是行不通的,我想我只是错了.当然我可以解析内容,但在我看来,美丽的汤旨在阻止我们这样做(如果我开始解析自己,我不妨解析整个文档......).如果有人能够告诉我如何实现这一点,我将感激不尽.如果有更好的方式然后BeautifulSoup,我会有兴趣听到它.
我有一些html,我想从中提取文本.这是html的一个例子:
<p>TEXT I WANT <i> – </i></p>
Run Code Online (Sandbox Code Playgroud)
现在,<p>
本文档中有很多标签.因此,find('p')
获取我想要提取的文本不是一个好方法.但是,该<i>
标记是文档中唯一的标记.所以,我以为我可以找到<i>
,然后去找父母.
我试过了:
up = soup.select('p i').parent
Run Code Online (Sandbox Code Playgroud)
和
up = soup.select('i')
print(up.parent)
Run Code Online (Sandbox Code Playgroud)
我已经有尝试过.parents
,我试过find_all('i')
,find('i')
...但我总是得到:
'list' object has no attribute "parent"
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
我有点像编码新手,我一直试图通过使用Beautiful Soup(用于从HTML中提取数据的Python库)从Rap天才http://genius.com/artists/Andre-3000中删除Andre 3000的歌词.和XML文件).我的最终目标是以字符串格式提供数据.这是我到目前为止:
from bs4 import BeautifulSoup
from urllib2 import urlopen
artist_url = "http://rapgenius.com/artists/Andre-3000"
def get_song_links(url):
html = urlopen(url).read()
# print html
soup = BeautifulSoup(html, "lxml")
container = soup.find("div", "container")
song_links = [BASE_URL + dd.a["href"] for dd in container.findAll("dd")]
print song_links
get_song_links(artist_url)
for link in soup.find_all('a'):
print(link.get('href'))
Run Code Online (Sandbox Code Playgroud)
所以我需要其他代码的帮助.如何将他的歌词变成字符串格式?然后我如何使用自然语言工具包(NLTK)来标记句子和单词.
我有一个csv文件("SomeSiteValidURLs.csv"),它列出了我需要抓取的所有链接.代码正在运行,将通过csv中的url,抓取信息并记录/保存在另一个csv文件("Output.csv")中.但是,由于我计划在网站的大部分区域(大于10,000,000页)进行此操作,因此速度非常重要.对于每个链接,爬行并将信息保存到csv大约需要1秒,这对于项目的大小来说太慢了.所以我已经整合了多线程模块,令我惊讶的是它根本没有加速,它仍然需要1个人链接.我做错什么了吗?还有其他方法可以加快处理速度吗?
没有多线程:
import urllib2
import csv
from bs4 import BeautifulSoup
import threading
def crawlToCSV(FileName):
with open(FileName, "rb") as f:
for URLrecords in f:
OpenSomeSiteURL = urllib2.urlopen(URLrecords)
Soup_SomeSite = BeautifulSoup(OpenSomeSiteURL, "lxml")
OpenSomeSiteURL.close()
tbodyTags = Soup_SomeSite.find("tbody")
trTags = tbodyTags.find_all("tr", class_="result-item ")
placeHolder = []
for trTag in trTags:
tdTags = trTag.find("td", class_="result-value")
tdTags_string = tdTags.string
placeHolder.append(tdTags_string)
with open("Output.csv", "ab") as f:
writeFile = csv.writer(f)
writeFile.writerow(placeHolder)
crawltoCSV("SomeSiteValidURLs.csv")
Run Code Online (Sandbox Code Playgroud)
使用多线程:
import urllib2
import csv
from bs4 import BeautifulSoup
import threading
def crawlToCSV(FileName):
with open(FileName, "rb") …
Run Code Online (Sandbox Code Playgroud) parallel-processing multithreading beautifulsoup web-scraping python-2.7
<span>
I Like
<span class='unwanted'> to punch </span>
your face
</span>
Run Code Online (Sandbox Code Playgroud)
如何打印"我喜欢你的脸"而不是"我喜欢打你的脸"
我试过这个
lala = soup.find_all('span')
for p in lala:
if not p.find(class_='unwanted'):
print p.text
Run Code Online (Sandbox Code Playgroud)
但它给出了"TypeError:find()不带关键字参数"
我是网络抓取游戏的新手。我正在尝试废弃以下网站: http://www.foodemissions.com/foodemissions/Calculator.aspx
使用在 Internet 上找到的资源,我整理了以下 HTTP POST 请求:
import urllib
from bs4 import BeautifulSoup
headers = {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Encoding': 'gzip,deflate,sdch',
'Accept-Language': 'en-US,en;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}
class MyOpener(urllib.FancyURLopener):
version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'
myopener = MyOpener()
url = 'http://www.foodemissions.com/foodemissions/Calculator.aspx'
# first HTTP request without form data
f = myopener.open(url)
soup_dummy = BeautifulSoup(f,"html5lib")
# parse and retrieve two vital form values
viewstate …
Run Code Online (Sandbox Code Playgroud) 为了解析网站的 html 代码,我决定使用BeautifulSoup
类和prettify()
方法。我写了下面的代码。
import requests
import bs4
response = requests.get("https://www.doviz.com")
soup = bs4.BeautifulSoup(response.content, "html.parser")
print(soup.prettify())
Run Code Online (Sandbox Code Playgroud)
当我在 Mac 终端上执行此代码时,未设置代码缩进。另一方面,如果我在 Windows cmd 或 PyCharm 上执行此代码,则所有代码都会设置。
你知道这其中的原因吗?
在 Google Chrome 的 Inspect element 工具中,您可以:right-click on an element > copy > copy js path
并且您会得到如下所示的一段不错的代码片段:document.querySelector("#left-container > div.left-content > div > div > ul")
它可以轻松地为您提供 Javascript 中选定元素的“路径”。
我的问题是,是否有一种简单的方法可以使用 BeautifulSoup 将这个 javascript 片段转换为 Python,它可以为我提供我想要的网页元素。
我正在尝试使用 Beautiful Soup 来解析 XML 文档。这是我实例化对象的代码BeautifulSoup
:
with open(filename, encoding='utf-8') as f_:
content = f_.read()
xml_cont = BeautifulSoup(content, 'lxml')
Run Code Online (Sandbox Code Playgroud)
当我运行我的代码时,我收到以下错误:
File "[omitted]", line 13, in [omitted]
xml_cont = BeautifulSoup(content, 'lxml')
File "/Users/Josh/Library/Python/3.7/lib/python/site-packages/bs4/__init__.py", line 228, in __init__
% ",".join(features))
bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?
Run Code Online (Sandbox Code Playgroud)
我快速搜索了一下,发现我需要lxml
用 pip 安装。我就这么做了。
pip3 install lxml
Run Code Online (Sandbox Code Playgroud)
但是,我仍然收到错误!有什么想法吗?
beautifulsoup ×10
python ×8
web-scraping ×4
html ×3
html-parsing ×2
python-3.x ×2
asp.net ×1
lxml ×1
nltk ×1
parsing ×1
pip ×1
python-2.7 ×1